Junit @value 注释字段用法 Java

Junit @value annotated field usage Java

如果我需要在 Junit 测试 class 中为 @Value 注释字段提供两个不同的值怎么办?这里我有一个布尔字段,它是 @Value 注释。所以我必须为可能为真也可能为假的场景编写 Junit 测试用例。

我用过@TestPropertySource(properties = "underwriting.skip=true").

对于以下字段

@Value("${underwriting.skip}")
protected Boolean skipUnderwriting;

但是为了测试某些代码,我需要在某些时候将值设置为 false。请建议。

您可以为不同的测试 class 使用不同的 @TestPropertySource 注释。根据您的需要,您可以在某些测试上使用@TestPropertySource(properties = "underwriting.skip=true"),在其他测试上使用@TestPropertySource(properties = "underwriting.skip=false")。

(注意:@TestPropertySource 属于您的测试 class,而不属于实际 class。)

以下解决方案对我有用。我使用 ReflectionTestUtils 将值设置为每个测试用例方法中的 属性 字段。

ReflectionTestUtils.setField(classToTest, "skipUnderwriting", Boolean.TRUE);