我编写了 Junit 测试类来测试特定方法。在此方法中处理的变量之一是 Spring 注入(inject),通过从属性文件中获取值。
下面是我的测试方法
@Test
public void myTestMethod() {
//invoking the method to be tested
Assert.assertTrue(updateGroceries());
}
这是要测试的类,
public class ToBeTested {
//Spring injected value
String categories;
public boolean updateGroceries() {
List<String> categoryList = StringUtils.convertStringToList(categories);
}
在上面的类中,类别变量是 spring 注入(inject)的。 这是属性文件内容:
categories = Dals,Pulses,Dry Fruits,Edible Oil
现在,在运行我的 Junit 方法时,执行失败,因为依赖注入(inject)失败。因为我要测试的代码在 tomcat 上运行。我想在不运行tomcat的情况下测试代码。请提出一些解决方案。
最佳答案
首先要运行 mockito,您需要在测试中启用它。
使用注释 @RunWith(MockitoJunitRunner.class)
或在测试开始时执行 Mockito.initMocks()
。
那么你的测试应该是这样的:
@RunWith(MockitoJunitRunner.class)
private YourTest{
@InjectMocks
ToBeTested toBeTested;
@Mock
ToBeTestedDependency dependency;
@Before
public void setUp(){
ReflectionTestUtils.setField(toBeTested, "categories",
"someCategory");
}
@Test
public void shouldDoThisOrThat(){
toBeTested.updateCategories();
}
}
不幸的是,mockito 不支持注入(inject) @Value
注释字段。您需要使用 ReflectionTestUtils
或使用 SpringJUnit4ClassRunner
设置运行测试,您需要使用 PropertyPlaceholder
配置来定义 spring 上下文以解析您拥有的属性作为您的 Value
键。在那里您可以找到引用 documentation and example Spring 测试方法。
希望这对您有所帮助。
关于java - 由于 spring 注入(inject),Junit 方法调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37259506/