I have a Spring 3.2 MVC application and am using the Spring MVC test framework to test GET and POST requests on the actions of my controllers. I am using Mockito to mock the
There is another solution with latest spring release using @WebMvcTest. Example below.
@RunWith(SpringRunner.class)
@WebMvcTest(CategoryAPI.class)
public class CategoryAPITest {
@Autowired
private MockMvc mvc;
@MockBean
CategoryAPIService categoryAPIService;
@SpyBean
Utility utility;
PcmResponseBean responseBean;
@Before
public void before() {
PcmResponseBean responseBean = new PcmResponseBean("123", "200", null, null);
BDDMockito.given(categoryAPIService.saveCategory(anyString())).willReturn(responseBean);
}
@Test
public void saveCategoryTest() throws Exception {
String category = "{}";
mvc.perform(post("/api/category/").content(category).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(jsonPath("messageId", Matchers.is("123")))
.andExpect(jsonPath("status", Matchers.is("200")));
}
}
Here we are loading only the CategoryAPI class which is a Spring rest controller class and rest all are mock. Spring has own version of annotation like @MockBean and and @SpyBean similar to mockito @Mock and @Spy.