Spring MVC单元测试控制器使用Mockito注入DAO对象



使用Mockito进行单位测试Spring MVC控制器时,如何注入DAO层对象。使用SpringJunit4ClassRunner类时,它总是给出@spy注释的null指针例外。

示例代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:**/evivecare-application-context-test.xml" })
@WithMockUser(username = "admin", roles={"ADMIN"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
public class ControllerTest {
    private MockMvc mockMvc;
     @Mock
     private SessionFactory sessionFactory;
     @Mock
     private Session session;
    @InjectMocks
    private FilterController filterController = new FilterController();
    @Spy
    private FilterService filterService= new FilterServiceImpl();
    @Autowired
    private FilterDAO filterDAO;
    @Mock
    private OperatorService userService;
    @Mock
    private EviveSpeechFilterService eviveSpeechFilterService;
    private TestContextManager testContextManager;

    @Before
    public void setup() throws Exception {
        // Process mock annotations
        MockitoAnnotations.initMocks(this);
        // Setup Spring test in standalone mode
        this.mockMvc = MockMvcBuilders.standaloneSetup(filterController).build();
        testContextManager = new TestContextManager(getClass());
        testContextManager.prepareTestInstance(this);
        filterDAO= new FilterDAOImpl(sessionFactory);
        Mockito.doReturn(session).when(sessionFactory).getCurrentSession();
    }
@Test
    public void testController200() throws Exception{
        Mockito.when(filterService.renameList("123","sdfgh")).thenReturn(false);
        Mockito.when(filterDAO.renameList("123","sdfgh")).thenReturn(false);
        this.mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/renameList")
                .sessionAttr("filterService", filterService)
                .sessionAttr("filterDAO", filterDAO)
                .param("listId", "1234567")
                .param("alternateName", "LIst Name"))
        .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk());
    }
}

在此测试案例中,filterService依次调用filterDAO,它始终返回null pointer exception。那么,我该怎么办来解决这个问题?

filterservice不是托管的bean,您可能需要将DAO注入构造函数,因为它不会在filterservice中自动自动化。

请参阅此问题,以获取更多信息:支持Spring(3(未实例化的班级自动化

相关内容

  • 没有找到相关文章

最新更新