java - 如何在构造函数中为 @Value 设置值以进行测试
问题描述
我想将值“忽略”设置为真假。目前已经能够在@Before 将其设置为true。但是我怎么也可以通过将其设置为 false 来进行测试。请注意,我需要将其作为构造函数初始化。
由于在构造函数中设置了值,因此通过 ReflectionTestUtils 设置值不起作用。我可以再次调用构造函数并将值设置为 false 但这将涉及此测试类中的许多设置以及所有相关的模拟等等,这会变得混乱。有没有解决的办法?
我有以下构造函数
// many other variables not relevant for this question
private final boolean ignore;
public Client(@Value("${a.error}") boolean ignore) {
// setting many other variables not relevant for this question
this.ignore = ignore;
}
测试时:
@Before
public void setUp() {
client = new Client(true);
//many other setups
}
// tests correctly fine cos I set the ignore to true
@Test
public void testing(){
// someMethod uses the ignore value to do some actions and return true / false
assertTrue(client.someMethod());
}
@Test
public void howToTestIgnoreSetToFalse(){
// ?
}
解决方案
这是一个常见的问题,我们开发了一个支持@InjectMocks
注入任意字段的 Junit5 扩展。这允许@Config
在测试 Spring 代码或许多其他场景时进行注入。
https://github.com/exabrial/mockito-object-injection
要使用:
<dependency>
<groupId>com.github.exabrial</groupId>
<artifactId>mockito-object-injection</artifactId>
<version>1.0.4</version>
<scope>test</scope>
</dependency>
这是一个注入布尔值的示例(不能用 Mockito 模拟)
@TestInstance(Lifecycle.PER_METHOD)
@ExtendWith({ MockitoExtension.class, InjectMapExtension.class })
public class MyControllerTest {
@InjectMocks
private MyController myController;
@Mock
private Logger log;
@Mock
private Authenticator auther;
@InjectionMap
private Map<String, Object> injectionMap = new HashMap<>();
@BeforeEach
public void beforeEach() throws Exception {
injectionMap.put("securityEnabled", Boolean.TRUE);
}
@AfterEach
public void afterEach() throws Exception {
injectionMap.clear();
}
public void testDoSomething_secEnabled() throws Exception {
myController.doSomething();
// wahoo no NPE! Test the "if then" half of the branch
}
public void testDoSomething_secDisabled() throws Exception {
injectionMap.put("securityEnabled", Boolean.FALSE);
myController.doSomething();
// wahoo no NPE! Test the "if else" half of branch
}
}
推荐阅读
- reactjs - 无法映射传递给我的 React Router 的 Link 组件的道具
- c# - 获取不在域中的计算机的域用户名
- asp.net-core - 将数组传递给 asp net core web api 操作方法 HttpGet
- c++ - 在 Linux 上链接 FMOD 库时未定义的参考
- json - 未定义导入的 json 文件的玩笑测试
- jenkins - Jenkins 配置页面需要很长时间才能加载
- ruby-on-rails - 扩展脚手架生成器
- ios - iOS 应用程序的用户界面似乎因未知原因被放大
- python - 如何通过使用列表中具有字典键的元素来访问字典值?
- c++ - 将 make 和 cmake 的 make 合并到构建系统中