1

There is a class.

class A {

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

}

Is it possible to write such a test that would test that method getValue() returns a key as a value.

There is my try:

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

That's nice, but this works only for one particular parameter value. But I, probably, need some kind of rule like "for each parameter it would return the parameter itself whatever value this parameter would have"


More context, what I'm actually trying to test:

Let's say we have a file with key=value entries, like a resource bundle. The method would return key if it could not find a value. For example if we search by "user.name", we going to have "Bob" if it is defined. If not - it would return key (user.name) itsef, because I do not want this method returns me null.

(This is actually a model of org.springframework.context.MessageSource.getMessage - it behaves similar way)

So.. updated

public String getValue(String key) {
    // some code ...might be here, but we care about a result
    if (valueWasFound) {
     return theValue;
    } 
    return key;
}
ses
  • 13,174
  • 31
  • 123
  • 226
  • 1
    We need more context of what you're trying to actually test. – Hiro2k Apr 16 '13 at 21:17
  • This is kind of duplication, technically. But my question comes from different perspective. I could not find the answer by key-words I was thinking of. – ses Apr 17 '13 at 14:06

2 Answers2

5

Use the returnsFirstArg method in AdditionalAnswers.

when(myMock.getValue(anyString())).then(returnsFirstArg());
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
2

What you want to do is explained in the 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"));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • It seems like a true.. but It looks almost as if I create a mock by aMock = new A() {@Overide getValue() {..whatever I want ..} } – ses Apr 16 '13 at 21:55
  • Except that by doing that, you wouldn't be able to mock any other method, and wouldn't be able to cerify expectations. The use of Answer is discouraged by Mockito. Returning hard-coded values is what is encouraged. – JB Nizet Apr 16 '13 at 21:59