Forming Mockito “grammars”

后端 未结 3 1941
忘了有多久
忘了有多久 2020-11-29 23:06

Mockito seems like a pretty sweet stubbing/mocking framework for Java. The only problem is I can\'t find any concrete documentation on the best ways of using their API. Comm

3条回答
  •  -上瘾入骨i
    2020-11-29 23:41

    Mockito often have several ways of doing things.

    I find myself using mostly:

    // Setup expectations
    when(object.method()).thenReturn(value);
    when(object.method()).thenThrow(exception);
    doThrow(exception).when(object.voidMethod());
    
    
    // verify things
    verify(object, times(2)).method();
    verify(object, times(1)).voidMethod();
    

    I've found that i can do 95% of what i need to with these three kinds of calls.

    Also, what version of Mockito are you using? "given" and "will" constructs are not present in the latest version (1.9.0+)

    However, there are cases where I want the return value or exception to respond to the input. In this case, you can use the Answer interface to inspect the method arguments and return an appropriate value.

    public class ReturnFirstArg implements Answer {
        public T answer(InvocationOnMock invocation) {
            return invocation.getArguments()[0];
        }
    }
    
    when(object.method(7)).thenAnswer(new ReturnFirstArg());
    

提交回复
热议问题