相关疑难解决方法(0)

如何从jUnit test访问Spring @Service对象

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

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

      @Resource
      private Properties appProperties;

}
Run Code Online (Sandbox Code Playgroud)

属性对象通过config-file配置.applicationContext.xml中

<util:properties id="appProperties" location="classpath:application.properties"/>
Run Code Online (Sandbox Code Playgroud)

我想测试一下这种实现的方法.

问题:如何从测试类访问MySystemServiceImpl-object,以便正确初始化Properties appProperties?

public class MySystemServiceImplTest {

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

    <bean id="testSubject" class="com.package.MySystemServiceImpl">
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我用这样的方式修改了测试类:

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

java junit spring

6
推荐指数
1
解决办法
8977
查看次数

标签 统计

java ×1

junit ×1

spring ×1