2011-10-11 61 views
5

情况:我有服务实现类,可以使用@Service注释并可以访问属性文件。如何从jUnit访问Spring @Service对象测试

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

     @Resource 
     private Properties appProperties; 

} 

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

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

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

问题:如何从测试类访问MySystemServiceImpl对象,使属性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. 我复制测试/资源目录application.properties

  2. 我复制了applicationContext.xml under test/resources dir。在应用方面,我添加新豆(应用程序属性的定义是已经在这里):

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

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

回答

7

另外,要做一个集成测试,我这样做。

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

    @Resource(name="myService") 
    public IMyService myService; 

然后使用该服务,你通常会。将应用上下文添加到您的测试/资源目录中

+0

谢谢,它有很大的帮助。 – dim1902

1

只需使用它的构造:

MySystemServiceImpl testSubject = new MySystemServiceImpl(); 

这是一个单元测试。单元测试与其他类和基础设施隔离地测试一个类。

如果您的类对其他接口有依赖关系,请嘲笑这些接口并使用这些mock作为参数创建对象。这就是依赖注入的要点:能够在对象内注入其他模拟实现,以便轻松测试此对象。

编辑:

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

+0

不幸的是,我无法修改该类。这就是为什么我必须坚持春季注射。在所有其余的我同意你的观点 – dim1902