java - 如何在 Spring Boot 中使用 @ConfigurationProperties 模拟类
问题描述
我有一个使用@ConfigurationProperties 自动连接另一个类的类。
带有@ConfigurationProperties 的类
@ConfigurationProperties(prefix = "report")
public class SomeProperties {
private String property1;
private String property2;
...
Autowires 类 SomeProperties 之上的类
@Service
@Transactional
public class SomeService {
....
@Autowired
private SomeProperties someProperties;
.... // There are other things
现在,我想测试SomeService类,在我的测试类中,当我模拟SomeProperties类时,我得到null
了所有属性的值。
测试班
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SomeProperties.class)
@ActiveProfiles("test")
@EnableConfigurationProperties
public class SomeServiceTest {
@InjectMocks
private SomeService someService;
@Mock // I tried @MockBean as well, it did not work
private SomeProperties someProperties;
如何模拟具有文件属性的SomePropertiesapplication-test.properties
。
解决方案
如果您打算绑定属性文件中的值,则不是在模拟 SomeProperties,在这种情况下,将提供 SomeProperties 的实际实例。
嘲笑:
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
@InjectMocks
private SomeService someService;
@Mock
private SomeProperties someProperties;
@Test
public void foo() {
// you need to provide a return behavior whenever someProperties methods/props are invoked in someService
when(someProperties.getProperty1()).thenReturn(...)
}
No Mock(someProperties
是一个真实的对象,它从某个属性源绑定它的值):
@RunWith(SpringRunner.class)
@EnableConfigurationProperties(SomeConfig.class)
@TestPropertySource("classpath:application-test.properties")
public class SomeServiceTest {
private SomeService someService;
@Autowired
private SomeProperties someProperties;
@Before
public void setup() {
someService = new someService(someProperties); // Constructor Injection
}
...
推荐阅读
- sql - SELECT COUNT(*) WHERE DATE_PART(...) 在 PostgreSQL/TimescaleDB 中很慢
- jenkins - 当 Jenkins 作业 DSL 插件尝试删除一些未引用的作业时,是什么导致堆栈溢出错误?
- xamarin - 两个搜索栏 Xamarin Forms
- java - 如何使用递归在java中创建一系列子字符串
- linux - 如何使 Linux Docker 映像文件系统不区分大小写?
- c++ - 以下代码中的函数模板有什么问题?
- android - 从firebase检索数据到textview返回null如何解决?
- google-apps-script - 从 html 输入更新/编辑谷歌表格行值
- spring-boot - o.lettuce.core.RedisException::io.netty.util.internal.OutOfDirectMemoryError 从 Redis 检索大对象 (2MB)
- python - 没有足够的积分 (2) 提供给 Voronoi