Mockito - returning the same object as passed into method

后端 未结 3 1983
花落未央
花落未央 2021-02-11 13:07

Let\'s imagine I have a following method in some service class:

public SomeEntity makeSthWithEntity(someArgs){
    SomeEntity entity = new SomeEntity();
    /**
         


        
相关标签:
3条回答
  • 2021-02-11 13:18

    Or better using mockito shipped answers

    when(mock.something()).then(AdditionalAnswers.returnsFirstArg())
    

    Where AdditionalAnswers.returnsFirstArg() could be statically imported.

    0 讨论(0)
  • 2021-02-11 13:26

    It can be done easy with Java 8 lambdas:

    when(mock.something(anyString())).thenAnswer(i -> i.getArguments()[0]);
    
    0 讨论(0)
  • 2021-02-11 13:27

    You can implement an Answer and then use thenAnswer() instead.

    Something similar to:

    when(mock.someMethod(anyString())).thenAnswer(new Answer() {
        public Object answer(InvocationOnMock invocation) {
            return invocation.getArguments()[0];
        }
    });
    

    Of course, once you have this you can refactor the answer into a reusable answer called ReturnFirstArgument or similar.

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