在Mockito中创建一个测试规则,例如"对于每个arg,该方法将返回基于此arg的答案"

ses*_*ses 1 java mockito

有一节课.

class A {

 public String getValue(String key) {
   return key;
 }

}
Run Code Online (Sandbox Code Playgroud)

是否有可能编写一个测试该方法getValue()将键作为值返回的测试.

有我的尝试:

  A aMock = mock(A.class);
  when(aMock.getValue("key")).thenReturn("key");
Run Code Online (Sandbox Code Playgroud)

这很好,但这只适用于一个特定的参数值.但我可能需要某种规则"for each parameter it would return the parameter itself whatever value this parameter would have"


更多背景,我实际上要测试的内容:

假设我们有一个包含key=value条目的文件,比如资源包.如果找不到值,该方法将返回键.例如,如果我们通过"user.name"搜索,如果定义了"Bob",我们就会拥有它.如果没有 - 它将返回key(user.name)itsef,因为我不希望这个方法返回我null.

(这实际上是一个模型org.springframework.context.MessageSource.getMessage- 它的行为类似)

所以......更新了

public String getValue(String key) {
    // some code ...might be here, but we care about a result
    if (valueWasFound) {
     return theValue;
    } 
    return key;
}
Run Code Online (Sandbox Code Playgroud)

Daw*_*ica 5

使用returnsFirstArg方法AdditionalAnswers.

when(myMock.getValue(anyString())).then(returnsFirstArg());
Run Code Online (Sandbox Code Playgroud)