我试图为我的程序中用于验证表单的简单bean编写单元测试。该bean使用@Component进行注释,并且有一个初始化使用的类变量

@Value("${this.property.value}") private String thisProperty;

我想为这个类中的验证方法编写单元测试,但是,如果可能的话,我想这样做而不使用属性文件。我这样做的原因是,如果我从属性文件中提取的值发生了变化,我希望它不影响我的测试用例。我的测试用例是测试验证值的代码,而不是值本身。

是否有一种方法可以在我的测试类中使用Java代码来初始化一个Java类,并在该类中填充Spring @Value属性,然后使用它来测试?

我确实发现这个如何,似乎是接近,但仍然使用一个属性文件。我宁愿全部都是Java代码。


当前回答

这似乎是可行的,尽管仍然有点啰嗦(我想要更短的东西):

@BeforeClass
public static void beforeClass() {
    System.setProperty("some.property", "<value>");
}

// Optionally:
@AfterClass
public static void afterClass() {
    System.clearProperty("some.property");
}

其他回答

SpringBoot自动为我们做了很多事情,但当我们使用@SpringBootTest注释时,我们认为所有事情都将由SpringBoot自动解决。

有很多文档,但最少的是选择一个引擎(@RunWith(SpringRunner.class)),并指出将用于创建上下文以加载配置的类(resources/applicationl.properties)。

简单地说,你需要引擎和上下文:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyClassTest .class)
public class MyClassTest {

    @Value("${my.property}")
    private String myProperty;

    @Test
    public void checkMyProperty(){
        Assert.assertNotNull(my.property);
    }
}

当然,如果你查看Spring Boot文档,你会发现数千种操作系统的方法。

如果可能的话,我会尝试在没有Spring Context的情况下编写这些测试。如果您在没有spring的测试中创建这个类,那么您可以完全控制它的字段。

要设置@value字段,您可以使用Springs ReflectionTestUtils -它有一个方法setField来设置私有字段。

@see JavaDoc: ReflectionTestUtils.setField(java.lang)Object, java . lang。管柱,java . lang . Object)

@ExtendWith(SpringExtension.class)    // @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class)

希望这能有所帮助。关键是ConfigDataApplicationContextInitializer获取所有道具数据

在测试方法中需要添加以下代码_

@Test
public void testIsValidFile() {

    AnyClass anyClass = new AnyClass();
    ReflectionTestUtils.setField(anyClass, "fieldName", "value");
    .........
    .........
}

在springboot 2.4.1中,我刚刚在我的测试中添加了注释@SpringBootTest,显然,在我的src/test/resources/application.yml中设置了spring.profiles.active = test

我使用@ExtendWith({SpringExtension.class})和@ContextConfiguration(类= {RabbitMQ.class, GenericMapToObject.class, ModelMapper.class, StringUtils.class})进行外部conf