代码之家  ›  专栏  ›  技术社区  ›  ses

在Mockito中创建一个测试规则,类似于“对于每个arg,方法都会返回一个基于此arg的答案”[重复]

  •  1
  • ses  · 技术社区  · 13 年前

    有一节课。

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

    有可能写这样一个测试来测试这种方法吗 getValue() 返回一个键作为值。

    这是我的尝试:

      A aMock = mock(A.class);
      when(aMock.getValue("key")).thenReturn("key");
    

    这很好,但这只适用于一个特定的参数值。但我可能需要某种规则,比如 "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;
    }
    
    2 回复  |  直到 13 年前
        1
  •  5
  •   Dawood ibn Kareem    13 年前

    使用 returnsFirstArg 中的方法 AdditionalAnswers .

    when(myMock.getValue(anyString())).then(returnsFirstArg());
    
        2
  •  2
  •   JB Nizet    13 年前

    你想做什么在 javadoc of Answer :

    when(mock.someMethod(anyString())).thenAnswer(new Answer() {
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            Object mock = invocation.getMock();
            return "called with arguments: " + args;
        }
    });
    
    // Following prints "called with arguments: foo"
    System.out.println(mock.someMethod("foo"));