【问题标题】:Junit method invocation fails due to spring injection由于 spring 注入,Junit 方法调用失败
【发布时间】:2016-05-16 17:13:00
【问题描述】:

我已经编写了 Junit 测试类来测试特定的方法。此方法中处理的变量之一是弹簧注入,通过从属性文件中获取值。

下面是我的测试方法

@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);
   }

在上面的类中,类别变量是弹簧注入的。 这是属性文件内容:

categories = Dals,Pulses,Dry Fruits,Edible Oil

现在在运行我的 Junit 方法时,执行失败,因为依赖注入失败。因为我要测试的代码在 tomcat 上运行。我想在不运行 tomcat 的情况下测试代码。请提出一些解决方案。

【问题讨论】:

    标签: java spring tomcat junit dependency-injection


    【解决方案1】:

    首先要运行 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 不支持注入 @Valueannotated 字段。您需要使用ReflectionTestUtils 或设置使用SpringJUnit4ClassRunner 运行您的测试,您需要使用PropertyPlaceholder 配置定义您的spring 上下文以解析您作为Value 键的属性。在那里您可以找到对弹簧测试方法的documentation and example 的参考。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      你应该看看 Mockito。当你使用 mockito 框架时,你可以为 spring 注入的值创建 mock。你应该阅读更多关于 mockito website 的内容。

      【讨论】:

        猜你喜欢
        • 2015-08-19
        • 1970-01-01
        • 1970-01-01
        • 2018-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-13
        相关资源
        最近更新 更多