mockito return value based on property of a parameter

前端 未结 5 1624
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 19:57

Normally when using mockito I will do something like

Mockito.when(myObject.myFunction(myParameter)).thenReturn(myResult);

Is it possible to do

相关标签:
5条回答
  • 2021-01-30 20:15

    You can do this with Mockito 3.6.0:

    when(mockObject.myMethod(anyString()))
        .thenAnswer(invocation -> myStringMethod(invocation.getArgument(0)));
    

    This answer is based on Sven's answer and Martijn Hiemstra's comment, with getArgumentAt() changed to getArgument().

    0 讨论(0)
  • 2021-01-30 20:16

    Here's one way of doing it. This uses an Answer object to check the value of the property.

    @RunWith(MockitoJUnitRunner.class)
    public class MyTestClass {
        private String theProperty;
        @Mock private MyClass mockObject;
    
        @Before
        public void setUp() {
            when(mockObject.myMethod(anyString())).thenAnswer(
                new Answer<String>(){
                @Override
                public String answer(InvocationOnMock invocation){
                    if ("value".equals(theProperty)){
                        return "result";
                    }
                    else if("otherValue".equals(theProperty)) {
                        return "otherResult";
                    }
                    return theProperty;
                }});
        }
    }
    

    There's an alternative syntax, which I actually prefer, which will achieve exactly the same thing. Over to you which one of these you choose. This is just the setUp method - the rest of the test class should be the same as above.

    @Before
    public void setUp() {
        doAnswer(new Answer<String>(){
            @Override
            public String answer(InvocationOnMock invocation){
                if ("value".equals(theProperty)){
                    return "result";
                }
                else if("otherValue".equals(theProperty)) {
                    return "otherResult";
                }
                return theProperty;
            }}).when(mockObject).myMethod(anyString());
    }
    
    0 讨论(0)
  • 2021-01-30 20:21

    In Java 8 it is even simpler than all of the above:

    when(mockObject.myMethod(anyString()))
        .thenAnswer(invocation -> 
            invocation.getArgumentAt(0, String.class));
    
    0 讨论(0)
  • 2021-01-30 20:27

    Here is how it would look like in Kotlin with mockito-kotlin library.

    mock<Resources> {
        on {
            mockObject.myMethod(any())
        } doAnswer {
            "Here is the value: ${it.arguments[0]}"
        }
    }
    
    0 讨论(0)
  • 2021-01-30 20:36

    Yes you can, using a custom argument matcher.

    See the javadoc of Matchers for more details, and more specifically ArgumentMatcher.

    0 讨论(0)
提交回复
热议问题