我在Spring Web模型 - 视图 - 控制器(MVC)框架应用程序中使用Mockito(在MIT许可下发布的Java的开源测试框架)进行了这个junit测试
我有这个测试:
@RunWith(MockitoJUnitRunner.class)
public class DeviceCatalogueControllerTest {
@InjectMocks
private DeviceCatalogueController controller;
@InjectMocks
protected SessionHelper sessionHelper;
@Mock
private MessageSource messageSource;
@Mock
protected CataloqueService cataloqueService;
@Autowired
protected ApplicationDao applicationDao;
@Before
public void setUpTest() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
@Test
public void testInitFormGet() throws Exception {
System.out.println ("SessionHelper sessionHelper --> " + sessionHelper);
//controller.initFormGet(searchForm, localeParam, request, response, model, locale)
controller.initFormGet(null, DEFAULT_LOCALE, request, response, null, new Locale(DEFAULT_LOCALE));
}
但运行测试时 applicationDao 为空
答案 0 :(得分:1)
您的测试类完全不了解Spring
。要在单元测试中使用Spring
,您必须使用正确的注释@RunWith(SpringJUnit4ClassRunner.class)
,而不是现在使用的@RunWith(MockitoJUnitRunner.class)
。
然后在@Before
方法中,您可以通过调用Mockito
来初始化MockitoAnnotations.initMocks(this);
模拟
您的测试类可以重新编码为:
@ContextConfiguration(locations = {"classpath:/application-context.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class DeviceCatalogueControllerTest {
@InjectMocks
private DeviceCatalogueController controller;
@InjectMocks
protected SessionHelper sessionHelper;
@Mock
private MessageSource messageSource;
@Mock
protected CataloqueService cataloqueService;
@Autowired
protected ApplicationDao applicationDao;
@Before
public void setUpTest() {
MockitoAnnotations.initMocks(this);
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
@Test
public void testInitFormGet() throws Exception {
System.out.println("SessionHelper sessionHelper --> " + sessionHelper);
//controller.initFormGet(searchForm, localeParam, request, response, model, locale)
controller.initFormGet(null, DEFAULT_LOCALE, request, response, null, new Locale(DEFAULT_LOCALE));
}
}
注意:在application-context.xml
@ContextConfiguration(locations = {"classpath:/application-context.xml"})
的正确xml路径