当前位置: 首页 > 面试题库 >

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

姜飞飙
2023-03-14
问题内容

情况 :我有使用@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. 这很容易-现在在我的测试类中,可以使用功能齐全的对象


问题答案:

或者,要进行集成测试。

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

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

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



 类似资料:
  • 我正在尝试从Spring Boot应用程序中的JUnit中访问application.properties或application-test.properties。 com.myservice.config.AppConfig: 主/资源/应用程序.属性: test.resources/application-test.properties JUnit类可以从main/resources/appl

  • 抱歉,这似乎是一个无用的行为,但我们有没有办法在Spring Boot(1.3.8.RELEASE)的应用程序上进行junit测试。java这个类除了启动Spring Boot应用程序之外什么都不做? 如下所示: 也许我可以尝试捕捉异常?但我还可以测试什么,以便JUnit测试SpringApplication呢。run()?任何例子都值得赞赏。谢谢大家!

  • 问题内容: 这是我使用的文件: component.xml ServiceImpl.java ServiceImplTest.java 错误: 问题答案: 确保已导入正确的程序包。如果我正确地记住,有两种不同的自动布线套件。应该 : 这对我来说也很奇怪: 这是一个适合我的示例:

  • 我需要jUnit测试的帮助,我的结果是json文件,我需要测试该文件的长度,问题是在jsonPath函数中没有这样的方法。 这里是我的测试方法,预期长度是7。如有任何帮助,我将不胜感激,谢谢

  • org.springframework.beans.factory.unsatisfiedDependencyException:创建名为“MyPackage.MongoServiceTest”的bean时出错:通过字段“Mongo Service”表示的不满足的依赖项;嵌套异常为org.springframework.beans.factory.noSuchBeanDefinitionExcep

  • 我的一个GAE类正在从HTML文件创建[datastore Entity][1]: 当我试图在JUnit测试中调用此方法时,会引发以下异常: 问题似乎是在我的代码示例的第一行中创建键。