mockito return value based on property of a parameter

前端 未结 5 1728
没有蜡笔的小新
没有蜡笔的小新 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: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(){
                @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(){
            @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());
    }
    

提交回复
热议问题