Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Spring中使用JUnit测试单个服务?_Java_Spring_Junit - Fatal编程技术网

Java 如何在Spring中使用JUnit测试单个服务?

Java 如何在Spring中使用JUnit测试单个服务?,java,spring,junit,Java,Spring,Junit,我有一个@Service类,它注入了一些属性。 既然注入过程工作正常,我想编写一个junit测试 如何定义JUnit测试而不必加载完整的应用程序上下文配置 @Service public class MyService { @Value("${test.property}") private String value; public String getValue() { return value; } } @RunWith(SpringJUnit4ClassRun

我有一个@Service类,它注入了一些属性。 既然注入过程工作正常,我想编写一个junit测试

如何定义JUnit测试而不必加载完整的应用程序上下文配置

@Service
public class MyService {
    @Value("${test.property}")
    private String value;

    public String getValue() {  return value; }
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {
   @Autowired
   private MyService service;

   @Test
   public void test() {
      assertNotNull(service.getValue());
   }
}
但当我运行这个:

java.lang.IllegalStateException: Neither GenericXmlContextLoader nor AnnotationConfigContextLoader was able to detect defaults, and no ApplicationContextInitializers were declared for context configuration 
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.processContextConfiguration(AbstractDelegatingSmartContextLoader.java:208)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:348)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:305)

您没有指定从何处注入测试中用@Autowired注释的字段的bean文件。您应该有如下内容:

@ContextConfiguration(locations = {
"classpath:applicationContext.xml",
"classpath:junit-applicationContext.xml"
})
看看


它有一个测试弹簧的模块。如果您的服务与数据库交互,它也会非常方便。

属性应该从哪里注入?application.properties文件我的问题更多的是它应该如何和/或为什么从那里获取属性。