gpt4 book ai didi

java - Mockito:结合@Autowired和@Mock

转载 作者:行者123 更新时间:2023-12-01 09:16:36 26 4
gpt4 key购买 nike

我在 Spring Web 模型- View - Controller (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为null

最佳答案

您的测试类完全不知道 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 使用正确的 xml 路径在@ContextConfiguration(locations = {"classpath:/application-context.xml"})

关于java - Mockito:结合@Autowired和@Mock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40509570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com