【问题标题】:How can I set a value for a string in a unit test?如何在单元测试中为字符串设置值?
【发布时间】:2020-09-14 15:39:48
【问题描述】:

在我目前的课程中,我有一个如下所示的字段:

 @Inject
 @ConfigValue(key = ConfigProperties.ADDRESS)
 private String address;

配置属性

  public static final String ADDRESS = //
        "42 Rue Cadet, 75009 Paris";

我有一个方法:

 ...... 
 private boolean isValidAddress() {
    if(address != null && address.equals("42 Rue Cadet, 75009 Paris")) {
        return true;
    } else {
        return false;
    }
 } 
 ......

我想创建一个单元测试来验证 isValidAddress() 方法,但我不知道如何设置地址。

例如:我想用这个地址进行测试 =“23 Rue Luvru, 75045 Paris”。 我正在考虑模拟 ConfigProperties,但我在 ConfigProperties 中没有任何方法可以设置地址的值。

有什么建议吗?

【问题讨论】:

  • 您可以通过反射设置address 或使其受保护而不是私有,但您也很难从测试中调用isValidAddress,因为它是私有的,除非您打算调用使用isValidAddress 的类的公共API 的其他部分。通常你只对公共 API 进行单元测试,而不是私有帮助方法。
  • @DavidConrad,是的,我在另一种方法中使用isValidAddress。通过反射你的意思是使用 setter 和 getter 吗?
  • 不,通过反射,我的意思是通过java.reflect.Field 访问该字段并直接设置其值。

标签: java unit-testing junit mocking mockito


【解决方案1】:

我们遇到了同样的问题,并且像很多人建议的那样使用反射来解决问题非常麻烦......所以我们编写了一个 JUnit5 扩展来解决这个确切的问题:

https://github.com/exabrial/mockito-object-injection

它的作用是将值注入到您的测试类中,这些值在您提供的 Map 中具有相同的键名。

@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();
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    相关资源
    最近更新 更多