@ConfigurationProperties配置类在mockito如何赋值
时间: 2024-08-17 14:00:14 浏览: 50
@ConfigurationProperties注解通常用于Spring Boot中,它允许从外部配置源(如application.properties文件)自动绑定配置到bean属性上。但在单元测试中,尤其是Mockito的场景下,如果你想要模拟这样的配置类,你需要做的是:
1. **手动创建模拟对象**:首先,你需要创建一个代表@ConfigurationProperties类的模拟对象。这通常是通过`@SpyBean`或者`@MockBean`配合`doReturn()`或`when().thenReturn()`来完成。
```java
import org.mockito.MockedStatic;
import org.springframework.boot.context.properties.ConfigurationProperties;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
// 示例
@MockedStatic(ConfigurationProperties.class)
@ConfigurationProperties(prefix = "my-config")
public class MyConfig {
private String myProperty;
// getters and setters...
public static void givenMyPropertyAs(String value) {
when(new MyConfig().getMyProperty()).thenReturn(value);
}
}
```
2. **设置模拟值**:在测试代码中,你可以调用静态方法`givenMyPropertyAs("your-value")`来设置模拟对象的属性值。
```java
@Test
void testMethodThatUsesConfig() {
MyConfig.myConfigGiven();
// 现在你可以在测试方法中假设myProperty已经被设置为"your-value"
String actualValue = myConfigInstance.getMyProperty(); // 这将返回"your-value"
// ... 测试你的业务逻辑
}
```