Unable to mock Service class in Spring MVC Controller tests

后端 未结 7 772
渐次进展
渐次进展 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:02

    This section, 11.3.6 Spring MVC Test Framework, in Spring document 11. Testing talks about it, but it is not clear in someway.

    Let's continue with the example in the document for explanation. The sample testing class looks as follow

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration("test-servlet-context.xml")
    public class AccountTests {
    
        @Autowired
        private WebApplicationContext wac;
    
        private MockMvc mockMvc;
    
        @Autowired
        private AccountService accountService;
    
        // ...
    
    }
    

    Suppose you have org.example.AppController as the controller. In the test-servlet-context.xml, you will need to have

    
        
    
    
    
        
    
    

    The document is missing the wiring part for the controller. And you will need change to setter injection for accountService if you are using field injection. Also, be noted that the value(org.example.AccountService here) for constructor-arg is an interface, not a class.

    In the setup method in AccountTests, you will have

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    
        // You may stub with return values here
        when(accountService.findById(1)).thenReturn(...);
    }
    

    The test method may look like

    @Test
    public void testAccountId(){
        this.mockMvc.perform(...)
        .andDo(print())
        .andExpect(...);  
    }
    

    andDo(print()) comes handy, do "import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;".

提交回复
热议问题