首页 > 解决方案 > 如何在构造函数中为 @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(){
    // ? 
}

标签: javaspringjunitmockito

解决方案


这是一个常见的问题,我们开发了一个支持@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
 }
}

推荐阅读