我有一个Spring-Boot应用程序,其中在应用程序中设置了默认属性。属性文件在类路径(src/main/resources/application.properties)。

我想用测试中声明的属性覆盖JUnit测试中的一些默认设置。属性文件(src/test/resources/test. Properties)

我通常为我的Junit测试有一个专用的配置类,例如。

package foo.bar.test;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

}

我最初认为在TestConfig类中使用@PropertySource("classpath:test.properties")可以达到目的,但是这些属性不会覆盖应用程序。属性设置(参见Spring-Boot参考文档- 23。外部化配置)。

然后我尝试使用-Dspring.config.location=classpath:test。属性。这是成功的——但是我不想为每次测试执行都设置这个系统属性。因此我把它放在代码中

@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

  static {
    System.setProperty("spring.config.location", "classpath:test.properties");
  }

}

不幸的是,这次也没有成功。

必须有一个简单的解决方案如何覆盖应用程序。使用test在JUnit测试中设置属性。我一定是忽略了这些特性


当前回答

您可以使用@TestPropertySource来覆盖application.properties中的值。从它的javadoc:

测试属性源可用于选择性地覆盖系统和应用程序属性源中定义的属性

例如:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public class ExampleApplicationTests {

}

其他回答

您可以使用@TestPropertySource来覆盖application.properties中的值。从它的javadoc:

测试属性源可用于选择性地覆盖系统和应用程序属性源中定义的属性

例如:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public class ExampleApplicationTests {

}

您也可以创建一个应用程序。在src/test/resources中的属性文件中,你的junit是在这里编写的。

您还可以使用元注释来具体化配置。例如:

@RunWith(SpringJUnit4ClassRunner.class)
@DefaultTestAnnotations
public class ExampleApplicationTests { 
   ...
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public @interface DefaultTestAnnotations { }

如果你真的想要/不得不使用System.setProperties(…),那么使用Junit扩展并注释测试类:

...
@ExtendWith(MyBeforeAllCallback.class)
public SomeTestClass ...

并使用回调函数的构造函数设置系统属性。

public MyBeforeAllCallback implements BeforeAllCallback {
    public MyBeforeAllCallback() {
        // wicket 9 workaround for java 17 / cglib issue.
        System.setProperty("wicket.ioc.useByteBuddy", "true");
        // ... whatever you want ...
        System.setProperty("whatever", "you need it badly");
    }
    void beforeAll(ExtensionContext context) {
        // ... empty
    }
}

另一种适用于覆盖测试中的一些属性的方法,如果你使用@SpringBootTest注释:

@SpringBootTest(properties = {"propA=valueA", "propB=valueB"})