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

dim1902:

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

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

      @Resource
      private Properties appProperties;

}

属性对象是通过config-file配置的。applicationContext.xml

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

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

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

public class MySystemServiceImplTest {

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

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

}

我不能简单地创建新的MySystemServiceImpl-比使用appProperties的方法会抛出NullPointerException。而且我无法直接在对象中插入属性-没有适当的设置方法。

只需在此处输入正确的步骤即可(感谢@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. 这很容易-现在在我的测试类中,可以使用功能齐全的对象

NimChimpsky:

或者,要进行集成测试。

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何为使用新的内部函数创建对象的Java类编写junit测试?

当arraylist包含对象时,如何使用Junit / Java测试compareTo?

如何用Spring Autowire编写JUnit测试?

在JUnit测试中更改Spring实现对象的最佳实践

如何JUnit测试从文件解析的对象

如何使用Spring JUnit集成测试检查数组中的每个对象是否具有特定属性?

如何在JUnit测试中从抽象类创建对象

模拟对象以进行JUnit测试

Spring @Service与对象服务

如何编写一个JUnit测试来比较两个对象列表的相等性?

使用自动装配的组件为Spring Boot Service应用程序编写JUnit测试用例

如何使用JUnit在Spring中测试ConfigurationProperties?

在测试环境中,如何通过URL访问ActiveStorage对象?

Kotlin在junit测试中共享同伴对象

Terraform-如何获取Azurerm密钥库访问策略的App Service对象ID?

如何退订Angular Service创建的可观察对象

如何为所有JUnit测试创建对象?

@FeignClient映射对象如何从Callee Service返回

如何在JUnit 5单元测试中为@Autowired模拟对象?

如何将对象(类)传递给Rest Service

如何在以@RunWith和@ContextConfiguration注释的jUnit测试中访问Spring上下文?

如何保存任何声明为类变量并在JUnit中的测试中初始化的对象

如何使用JUnit测试对象数组

使用Junit测试Spring MVC和Hibernate的DAO层和Service层的步骤

在JUnit4测试中,在@Before和@After中访问对象的同一实例

如何使用内部对象创建进行JUnit测试

Spring MockMvc:如何在初始化测试时访问请求对象

如何在 Kotlin 中测试/访问伴随对象扩展函数?

mapstruct 对象的 Junit 测试