Spring 和 class 的 Web 集成测试用 @ConditionaOnProperty 注释

Spring and web integration test of class annotated with @ConditionaOnProperty

我正在使用 Spring Boot 1.4.2。

我有一个服务注释如下

@Service
@ConditionalOnProperty("${my.property.enabled:false}")
public class MyService {

}

我想通过集成测试来测试它,例如

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyServiceTest {

    @Autowired
    private MyService myService;

}

该服务未在测试中自动装配。我想避免在测试文件夹内的属性文件中设置 属性 。我不能通过 MyServiceTest 中的这样一个注释直接启用 属性 吗?

更新

正如 Stephane 在评论中提到的,下面演示的用于测试目的的 属性 内联可以直接通过 properties 参数在 @SpringBootTest 中发生,在这种情况下您不需要@TestPropertySource:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, 
                properties = { "my.property.enabled = true" })
public class MyServiceTest {

    @Autowired
    private MyService myService;

}

原答案

您可以直接使用 @TestPropertySource:

在测试配置 class 中内联所需的 属性
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = { "my.property.enabled = true" })
public class MyServiceTest {

    @Autowired
    private MyService myService;

}

另请注意,您定义的注释不起作用,也许您打算使用 @ConditionalOnExpression,在这种情况下它会起作用:

@Service
@ConditionalOnExpression("${my.property.enabled:false}")
public class MyService {

}

但是 @ConditionalOnProperty 更具表现力,在您的情况下可以写成:

@Service
@ConditionalOnProperty(prefix="my.property" , name = "enabled", havingValue = "true")
public class MyService {

}