【问题标题】:Spring and web integration test of class annotated with @ConditionaOnProperty使用 @ConditionaOnProperty 注释的类的 Spring 和 Web 集成测试
【发布时间】:2017-04-30 09:51:11
【问题描述】:

我使用的是 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 中的此类注释直接启用该属性吗?

【问题讨论】:

  • 准确了解您要完成的工作会有所帮助。最好简单地为该测试创建一个 @Configuration 类,专门声明一个 @Bean MyService 无条件。
  • 这种方法看起来很有趣。如何在 MyServiceTest 中执行特定配置?
  • 我不确定新的引导测试魔法是如何工作的;我通常使用@ContextConfiguration。您可以尝试在测试类上声明一个(静态)@Configuration 嵌套类,看看它是否被拾取。

标签: java spring spring-mvc spring-boot conditional


【解决方案1】:

更新

正如 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 直接在测试配置类中内联所需的属性:

@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 {

}

【讨论】:

  • 也许你可以更新你的答案,提到SpringBootTest 有一个properties 的快捷方式。所以它会像@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ""my.property.enabled=true")
猜你喜欢
  • 1970-01-01
  • 2021-06-26
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多