当使用mockito对单元测试Spring mvc控制器时,如何注入dao层对象。在使用SpringJUnit4ClassRunner类时,它总是使用@Spy注释给出空指针异常。
示例代码:
@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
始终返回function validateForm()
{
debugger;
var fields = ["surname", "name", "dob"]
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if (document.getElementsByName(fieldname)[0].value === "") {
alert(fieldname + " can not be empty");
return false;
}
}
return true;
}
function doit2() {
if(document.getElementById('two').style.display == 'none'){
document.getElementById('two').style.display = 'block';
} else {
if(validateForm()){
document.getElementById('two').style.display = 'none';
}
}
}
。
那么,我该怎么做才能解决这个问题呢?
答案 0 :(得分:0)
FilterService不是托管bean,您可能需要在构造函数中注入dao,因为它不会在filterService中自动装配。
有关详细信息,请参阅此问题:Support for autowiring in a class not instantiated by spring (3)