java - 如何从 jUnit 测试访问 Spring @Service 对象

标签 java spring junit

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

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

      @Resource
      private Properties appProperties;

}

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

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

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

问题:如何以正确初始化属性 appProperties 的方式从测试类访问 MySystemServiceImpl 对象?

public class MySystemServiceImplTest {

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

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

}

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

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

  1. 我将 application.properties 复制到 test/resources 目录下。

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

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

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

最佳答案

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

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

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

然后像往常一样使用该服务。将应用程序上下文添加到您的测试/资源目录

关于java - 如何从 jUnit 测试访问 Spring @Service 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7723951/

相关文章:

java - 由于 ConnectException,Hadoop 映射失败

java - IBM Bluemix : Will it work for a Spring-MVC , Postgresql 与我们的域名

java - Spring : Need for the contextConfigLocation?

java - 从代码覆盖中排除枚举类?

java - 求助理解Java Reflection --> Android ParcelableContainer

Java-仅在某些区域绘制

javascript - 如何使用 jquery/javascript、Spring 按 id 删除?

intellij-idea - 如何在 IntelliJ IDEA 15 中的 gradle 项目上启用 Infinitest?

Java:当该字段未公开时,如何模拟该字段的方法?

java - 在java中的相似类之间复制字段