Unable to mock Service class in Spring MVC Controller tests

后端 未结 7 801
渐次进展
渐次进展 2020-12-02 06:44

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

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 07:01

    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.

提交回复
热议问题