【问题标题】:How to access Spring @Service object from jUnit test如何从 jUnit 测试访问 Spring @Service 对象
【发布时间】:2011-10-11 09:31:16
【问题描述】:

情况:我有使用 @Service 注释的服务实现类,可以访问属性文件。

@Service("myService")
public class MySystemServiceImpl implements SystemService{

      @Resource
      private Properties appProperties;

}

属性对象是通过配置文件配置的。 applicationContext.xml

<util:properties id="appProperties" location="classpath:application.properties"/>

我想测试一下这个实现的一些方法。

问题:如何从测试类中访问 MySystemServiceImpl-object 以使属性 appProperties 正确初始化?

public class MySystemServiceImplTest {

    //HOW TO INITIALIZE PROPERLY THROUGH SPRING? 
    MySystemServiceImpl testSubject;

    @Test
    public void methodToTest(){
        Assert.assertNotNull(testSubject.methodToTest());
    }     

}

我不能简单地创建新的 MySystemServiceImpl - 使用 appProperties 的方法会引发 NullPointerException。而且我不能直接在对象中注入属性 - 没有合适的 setter 方法。

只需在此处输入正确的步骤(感谢@NimChimpsky 的回答):

  1. 我在 test/resources 目录下复制了 application.properties

  2. 我在 test/resources 目录下复制了 applicationContext.xml。在应用程序上下文中,我添加了新的 bean(应用程序属性的定义已经在这里):

    <bean id="testSubject" class="com.package.MySystemServiceImpl">
    
  3. 我以这种方式修改了测试类:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"/applicationContext.xml"})
    public class MySystemServiceImplTest {
    
       @Autowired
       MySystemServiceImpl testSubject;
    
    }
    
  4. 这就是诀窍 - 现在在我的测试类中,功能齐全的对象可用

【问题讨论】:

    标签: java spring junit


    【解决方案1】:

    或者,要进行集成测试,我会这样做。

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"/applicationContext-test.xml"})
    @Transactional
    public class MyTest {
    
        @Resource(name="myService")
        public IMyService myService;
    

    然后像往常一样使用该服务。将应用上下文添加到您的 test/resources 目录

    【讨论】:

      【解决方案2】:

      只需使用它的构造函数:

      MySystemServiceImpl testSubject = new MySystemServiceImpl();
      

      这是一个单元测试。单元测试将一个类与其他类和基础设施隔离开来进行测试。

      如果您的类依赖于其他接口,请模拟这些接口并使用这些模拟作为参数创建对象。这就是依赖注入的全部意义:能够在对象内注入其他模拟实现,以便轻松测试该对象。

      编辑:

      您应该为您的属性对象提供一个设置器,以便能够为每个单元测试注入您想要的属性。注入的属性可能包含标称值、极值或不正确的值,具体取决于您要测试的内容。现场注入是实用的,但不适合单元测试。使用单元测试时应该首选构造函数或设置器注入,因为依赖注入的主要目标正是能够在单元测试中注入模拟或特定依赖项。

      【讨论】:

      • 不幸的是我没有能力修改类。这就是为什么我必须坚持使用 Spring 注入。其余的我都同意你的观点
      • 不注射有什么坏处吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 2016-10-04
      • 2018-02-25
      相关资源
      最近更新 更多