Monday, March 21, 2016

Mockito Tips



https://dzone.com/articles/mockito-pros-cons-and-best
Match null or not
- any(): Matches anything, including nulls and varargs.
- any(Class<T> type): Matches any object of given type, excluding nulls.
- anyInt() etc: Since Mockito 2.1.0, only allow valued Integer, thus null is not anymore a valid value. As primitive wrappers are nullable, the suggested API to match null wrapper would be isNull().
- [ArgumentMatchers.isNull()](https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentMatchers.html#isNull--)

https://testing.googleblog.com/2013/05/testing-on-toilet-dont-overuse-mocks.html
Don’t Overuse Mocks
Don't Replace Asserts with Verify

https://static.javadoc.io/org.mockito/mockito-core/2.28.2/org/mockito/Mockito.html

http://wiki.c2.com/?ArrangeActAssert



"Arrange-Act-Assert"

  1. Arrange all necessary preconditions and inputs.
  2. Act on the object or method under test.
  3. Assert that the expected results have occurred.
https://medium.com/@pjbgf/title-testing-code-ocd-and-the-aaa-pattern-df453975ab80
Your test code should respect most, if not all, rules of production code. It should avoid meaningless magic numbers, should avoid violating principles like DRY, YAGNI, SRP and KISS.

https://tedvinke.wordpress.com/2014/02/13/mockito-why-you-should-not-use-injectmocks-annotation-to-autowire-fields/
People like the way how Mockito is able to mock Spring’s auto-wired fields with the @InjectMocks annotation. When I read this post of Lubos Krnac last week, I thought I should explain why I think the use of InjectMocks is a bad signal and how you should avoid it. Hint: it’s about visibility.

Mockito will try to inject mocks only either by constructor injection, setter injection, or property injection in order and as described below. If any of the following strategy fail, then Mockito won’t report failure; i.e. you will have to provide dependencies yourself.
我不知道Test Double翻译成中文是什么,测试替身?Test Double就像是陈龙大哥电影里的替身,起到以假乱真的作用

A stub is an object that doesn't know how to behave on its own. Its methods only return what you tell them to return.

Mockito can create both mocks and stubs (and they even let the same object behave as both a mock and stub)
https://stackoverflow.com/questions/37527038/mockito-object-is-not-an-instance-of-declaring-class/37528479
https://stackoverflow.com/questions/41050029/mockito-cannot-mock-this-class
Mockito object is not an instance of declaring class
Your Java runtime version is from March 2014; plenty of bugs have been fixed in the VM ever since and you should really upgrade. I am 99% sure that this problem is related to type annotations (@NonNull) which were introduced in this version for the first time in this exact release. I am sure that your problem will go away if you upgrade your VM.
I can successfully execute your proposed test with a recent build of the HotSpot VM.
https://stackoverflow.com/questions/2276271/how-to-make-mock-to-void-methods-with-mockito
Mockito.doThrow(new Exception()).when(instance).methodName();
or if you want to combine it with follow-up behavior,
Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Mockito.doCallRealMethod().when(<objectInstance>).<method>();
<objectInstance>.<method>();


The when syntax won't work with a void method (it won't fit within the when), and doReturndoesn't apply when there's no return value. doCallRealMethod is likely the answer you want.
doCallRealMethod().when(instance).voidFunction();

Calling Mockito.when multiple times on same object?
https://stackoverflow.com/questions/8088179/using-mockito-with-multiple-calls-to-the-same-method-with-the-same-arguments
You can even chain doReturn() method invocations like this
doReturn(null).doReturn(anotherInstance).when(mock).method();
As previously pointed out almost all of the calls are chainable.
So you could call
when(mock.method()).thenReturn(foo).thenReturn(bar).thenThrow(new Exception("test"));

//OR if you're mocking a void method and/or using spy instead of mock

doReturn(foo).doReturn(bar).doThrow(new Exception("Test").when(mock).method();

http://www.javarticles.com/2015/08/mockito-argumentcaptor-example.html
    public void argumentValuesVerificationWithArgumentCapture() {       
        Employee empJoe = new Employee("Joe");
        empJoe.setEmpManager(empManager);
        empJoe.setTaxManager(taxManager);
        empJoe.calculateNetPay();
         
        ArgumentCaptor<EmpEvent> empEventArgCaptor = ArgumentCaptor.forClass(EmpEvent.class);
        verify(empManager).recordEvent(empEventArgCaptor.capture());
         
        assertEquals(empEventArgCaptor.getValue().getData(), 1000L);
        assertEquals(empEventArgCaptor.getValue().getEventType(), EventType.TAX_CALCULATED);
        assertEquals(empEventArgCaptor.getValue().getEmp(), empJoe);
    }
http://stackoverflow.com/questions/37543879/mockito-mock-a-method-call-in-constructor
Sometimes, we may have to create @InjectMocks object manually
- when we call mocked methods in its constructor
http://stackoverflow.com/questions/33397643/manually-instantiating-the-injectmock-annotated-field
If you use the runner, you don't need to call MockitoAnnotations.initMocks() yourself - the runner calls it for you.
Usually we go for the runner. When you want to use other runners, though (like Spring's), you can call .initMocks() yourself.
Just to be clear, the MockitoAnnotations.initMocks(this) will:
  • Instantiate the field annotated with @InjectMocks
  • Create a mock version of every field annotated with @Mock
  • Inject the @Mocks in the @InjectMocks variable's fields (or call its constructors or use its setters - it depends on what kind of Dependency Injection you use)
https://www.journaldev.com/21876/mockito-argument-matchers-any-eq
Mockito argument matchers can be used only with when() and verify() methods
https://www.baeldung.com/mockito-argument-matchers
There are two more points to take care when matchers are used:
  • We can’t use them as a return value, an exact value is required when stubbing calls
  • Finally, we can’t use argument matchers outside of verification or stubbing
In the last case, Mockito will detect the misplaced argument and throw an InvalidUseOfMatchersException.
A bad example could be:
1
2
String orMatcher = or(eq("poppy"), endsWith("y"));
verify(mock).analyze(orMatcher);
The way to implement the above code is:
1
verify(mock).analyze(or(eq("poppy"), endsWith("y")));
Mockito also provides AdditionalMatchers to implement common logical operations (‘not’, ‘and’, ‘or’) on ArgumentMatchers that match both primitive and non-primitive types:
1
verify(mock).analyze(or(eq("poppy"), endsWith("y")));
https://www.journaldev.com/21892/mockito-argumentcaptor-captor-annotation
Mockito ArgumentCaptor is used to capture arguments for mocked methods. ArgumentCaptor is used with Mockito verify() methods to get the arguments passed when any method is called. This way, we can provide additional JUnit assertions for our tests.

We can create ArgumentCaptor instance for any class, then its capture() method is used with verify() methods.
Finally, we can get the captured arguments from getValue() and getAllValues() methods.
getValue() method can be used when we have captured a single argument. If the verified method was called multiple times then getValue() method will return the latest captured value.
how to capture arguments that are passed into mocked methods
Firstly, we should create an instance of ArgumentCaptor with appropriate type parameter. Then, we should callArgumentCaptor.capture() during the verification phase of our test:
Mockito.verify(personRepository).delete(captor.capture());
    Person captured = captor.getValue();
    Assertions.assertThat(captured.getName()).isEqualTo("deleted");




https://asolntsev.github.io/en/2016/10/11/mockito-2.1/

First, you will need to replace import

A lot of imports. In many files. Replace these lines:
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyVararg; // not needed - replaced by any()
by these lines:
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;

1) Matcher any() does not match null anymore

This code worked before:
doNothing().when(service).calculateAmounts(any(BigDecimal.class), anyString());
But doesn’t work anymore, if some of parameters are null. Yes, my friend! You will need to rework all your tests that pass null instead of realistic value.
And it’s great, because the new code is really better:
doNothing().when(service).calculateAmounts(order.amount, order.currency);
Or this way:
doNothing().when(service).calculateAmounts(new BigDecimal("100.00"), "EEK");
If you really need to pass null parameter, you can still do it. Just pass null explicitly using isNull matcher:
doNothing().when(service).calculateAmounts(any(BigDecimal.class), isNull());

2) Matcher anyInt() does not match long anymore

This code worked with Mockito 1.x, but fails with Mockito 2.x:
when(mqService.send(anyString(), anyInt())).thenReturn("transfer-ref");
You need to replace anyInt() by anyLong() for Mockito 2.1:
 when(mqService.send(anyString(), anyLong())).thenReturn("transfer-ref");
By the way, even better solution is to avoid both mock and any and just create plain objects:
service.checkForMoratorium(new Mandate(), new LoanApplication());

6) You will find out that anyList() and anyCollection() are now different things

For example, this code worked with Mockito 1:
  @Test
  public void domesticPaymentInForeignCurrencyCanBeEnabled() {
    doCallRealMethod().when(Payments.accountService).forOperation(anyList(), eq(DOMESTIC));

    Collection<Account> accounts = ...
    
    return accountService.forOperation(accounts, DOMESTIC);
Note that mock in the first line uses anyList(), but the code actually passes variable accounts of type Collection (thought it’s actually List).
Mockito 2 doesn’t allow it anymore. You need to mock more precisely using anyCollection().
https://turreta.com/2015/11/12/find-out-if-an-object-is-a-mock-or-spy-in-mockito/
    public void test_dependencies_mock_or_spy() {
        // dependency1 is a mock object
        Assert.assertTrue(Mockito.mockingDetails(dependency1).isMock());
        // dependency1 is not a spy object
        Assert.assertFalse(Mockito.mockingDetails(dependency1).isSpy());
        // dependency2 is not a mock object
        Assert.assertTrue(Mockito.mockingDetails(dependency2).isMock());
        // dependency2 is a spy object
        Assert.assertTrue(Mockito.mockingDetails(dependency2).isSpy());
    }

http://www.megster.net/2014/unit-testing-log4j-method-calls-with-junit-and-mockito
http://jugglingcode.blogspot.com/2011/02/code.html
Mockito normally throws an exception when you try to inline a mock as follows:
?
1
2
Zoo zoo = mock(Zoo.class);
when(zoo.getAnimal()).thenReturn(mock(Animal.class));

One work-around is to do the following:
?
1
2
3
Zoo zoo = mock(Zoo.class);
Animal animal = mock(Animal.class);
when(zoo.getAnimal()).thenReturn(animal);
https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2
Mockito JUnit runner and rule can now detect unused stubs. It is possible to revert this behaviour.
// detect unused stubs
@RunWith(MockitoJUnitRunner.class)

// don't detect, old behaviour
@RunWith(MockitoJUnitRunner.Silent.class)
or with the rule
// detect unused stubs
@Rule public MockitoRule mrule = MockitoJUnit.rule();

// don't warn user about misusage, old behaviour
@Rule public MockitoRule mrule = MockitoJUnit.rule()
                                             .silent();


dependencies { testCompile "org.mockito:mockito-core:2.0.57-beta" }
https://github.com/mockito/mockito/wiki/Declaring-mockito-dependency
Legacy builds with manual dependency management can use 1.* "mockito-all" distribution. It can be downloaded from Mockito's Bintray repository or Bintray's jcenter. "mockito-all" distribution has been discontinued in Mockito 2.*.
https://github.com/powermock/powermock/issues/422
I mentioned in my answers above, PowerMock can work only with JaCoCo Offline instrumentation. PowerMock uses custom class loader and reads class from disk, so all agents changes are invisible for PowerMock.
https://github.com/powermock/powermock/wiki/MockitoUsage
http://arinadevinfo.blogspot.com/2015/09/how-to-mock-static-methods-during-unit.html
@RunWith(PowerMockRunner.class)
@PrepareForTest(SystemUtils.class)
public class SystemUtilsTest {

    @Test
    public void testGetHostName() throws UnknownHostException {
        PowerMockito.mockStatic(InetAddress.class);
        PowerMockito.when(InetAddress.getLocalHost())
                .then(new ThrowsExceptionClass(UnknownHostException.class));
        String actualValue = SystemUtils.getHostName();
        assertEquals("On exception expected unknown value", SystemUtils.UNKNOWN_HOST, actualValue);
    }
}
http://stackoverflow.com/questions/28836778/usages-of-dothrow-doanswer-donothing-and-doreturn-in-mockito
doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.
public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));
https://code.google.com/archive/p/mockito/issues/489
http://stackoverflow.com/questions/38567326/is-it-discouraged-to-use-spy-and-injectmocks-on-the-same-field
It is uncommon, and arguably inappropriate, to use @Spy and @InjectMocks together.
@InjectMocks works as a sort of dependency injection for the system under test: If you have a test that defines a @Mock or @Spy of the right type, Mockito will initialize any fields in your @InjectMocks instance with those fields. This might be handy if you haven't otherwise structured your system-under-test for dependency injection (or if you use a DI framework that does field injection) and you want to replace those dependencies with mocks. It can be pretty fragile—unmatched fields will be silently ignored and will remain null if not set in an initializer—but remains a decent annotation for your system under test.
@Spy, like @Mock, is designed to set up test doubles; you should use it when you have a collaborator that you want to stub or verify. Note there that @Spy and @Mock are always meant for dependencies, and not for your system under test.
Ideally, you should not have any class that fulfills both roles in the same test, or else you may find yourself writing a test that painstakingly tests behavior that you've stubbed rather than actual production behavior. In any case it will be more difficult to tell exactly what the test covers versus the behavior you've stubbed.
Of course, this may not apply if you're trying to use Mockito to test a single method in isolation, and you want to stub calls to one method while testing the other. However, this might also be an indication that your class is violating the Single Responsibility Principle, and that you should break down the class into multiple independent classes that work together. Then, in your test, you can allow instances to have exactly one role and never need both annotations at once.
http://stackoverflow.com/questions/15020747/how-should-i-use-org-mockito-additionalmatchers-gt
You should use Hamcrest's greaterThan for this case. gt is for verifying arguments of method calls in mock objects:
        assertThat(17, is(org.hamcrest.Matchers.greaterThan(10)));

        list.add(17);
        verify(list).add(org.mockito.AdditionalMatchers.gt(10));
http://stackoverflow.com/questions/29611893/mockito-notamockexception
Note, however, that matchers can't be used in doReturn calls regardles of how you're mocking or spying your object. A return value must be a concrete object.
http://www.baeldung.com/mockito-spy
When Mockito creates a mock – it does so from the Class of an Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it.
On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.

http://stackoverflow.com/questions/11620103/mockito-trying-to-spy-on-method-is-calling-the-original-method
https://static.javadoc.io/org.mockito/mockito-core/2.7.15/org/mockito/Mockito.html#13
You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).
Real spies should be used carefully and occasionally, for example when dealing with legacy code.
Spying on real objects can be associated with "partial mocking" concept
List list = new LinkedList(); List spy = spy(list); //optionally, you can stub out some methods: when(spy.size()).thenReturn(100); //using the spy calls *real* methods spy.add("one"); spy.add("two"); //prints "one" - the first element of a list System.out.println(spy.get(0)); //size() method was stubbed - 100 is printed System.out.println(spy.size()); //optionally, you can verify verify(spy).add("one"); verify(spy).add("two");

Important gotcha on spying real objects!

  1. Sometimes it's impossible or impractical to use when(Object) for stubbing spies. Therefore when using spies please consider doReturn|Answer|Throw() family of methods for stubbing. Example:
    
       List list = new LinkedList();
       List spy = spy(list);
    
       //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
       when(spy.get(0)).thenReturn("foo");
    
       //You have to use doReturn() for stubbing
       doReturn("foo").when(spy).get(0);
Unit Testing Servlet with Mocks
http://www.marklai.com/2012/06/unit-testing-servlet-with-mocks.html
        HttpServletResponse mockResponse = mock(HttpServletResponse.class);
        ServletOutputStream mockOutput = mock(ServletOutputStream.class);

        when(mockResponse.getOutputStream()).thenReturn(mockOutput);

        new HiNemoServlet().doGet(mockRequest, mockResponse);

        verify(mockResponse).setContentType("plain/text");
        verify(mockOutput).println("Hi Nemo!");

https://www.grobmeier.de/mock-testing-a-magnolia-servlet-filter-mockito-31102012.html
when(request.getParameter("requestParam")).thenReturn("value");
Map parameterMap = new HashMap();
parameterMap.put("requestParam", new String[] { "value" }); when(request.getParameterMap()).thenReturn(parameterMap);
http://johannesbrodwall.com/2009/10/24/testing-servlets-with-mockito/

http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html

2. How about some stubbing?


 //You can mock concrete classes, not just interfaces
 LinkedList mockedList = mock(LinkedList.class);

 //stubbing
 when(mockedList.get(0)).thenReturn("first");
 when(mockedList.get(1)).thenThrow(new RuntimeException());

 //following prints "first"
 System.out.println(mockedList.get(0));

 //following throws runtime exception
 System.out.println(mockedList.get(1));

 //following prints "null" because get(999) was not stubbed
 System.out.println(mockedList.get(999));

 //Although it is possible to verify a stubbed invocation, usually it's just redundant
 //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
 //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.
 verify(mockedList).get(0);

7. Making sure interaction(s) never happened on mock


 //using mocks - only mockOne is interacted
 mockOne.add("one");

 //ordinary verification
 verify(mockOne).add("one");

 //verify that method was never called on a mock
 verify(mockOne, never()).add("two");

 //verify that other mocks were not interacted
 verifyZeroInteractions(mockTwo, mockThree);

5. Stubbing void methods with exceptions


   doThrow(new RuntimeException()).when(mockedList).clear();

   //following throws RuntimeException:
   mockedList.clear();

12. doReturn()|doThrow()doAnswer()|doNothing()|doCallRealMethod() family of methods

Stubbing void methods requires a different approach from when(Object) because the compiler does not like void methods inside brackets...
doThrow(Throwable...) replaces the stubVoid(Object) method for stubbing voids. The main reason is improved readability and consistency with the family of doAnswer() methods.
Use doThrow() when you want to stub a void method with an exception:

   doThrow(new RuntimeException()).when(mockedList).clear();

   //following throws RuntimeException:
   mockedList.clear();
 
You can use doThrow()doAnswer()doNothing()doReturn() and doCallRealMethod() in place of the corresponding call with when(), for any method. It is necessary when you
  • stub void methods
  • stub methods on spy objects (see below)
  • stub the same method more than once, to change the behaviour of a mock in the middle of a test.
but you may prefer to use these methods in place of the alternative with when(), for all of your stubbing calls.
http://stackoverflow.com/questions/11462697/forming-mockito-grammars


In order to use Mockito, you need to understand one basic philosophy of Mockito: Stubbing and Verification is separated. Therefore, the "Verify/Do" you mentioned is in fact doing the "Verification" job, while the other 4 "grammars" is for stubbing. Stubbing define how the mock object will react in different situation. Verification is to make sure what the mocks is invoked as expected, in previous invocation to system under test (SUT)
http://www.baeldung.com/mockito-behavior
when(listMock.add(anyString())).thenReturn(false);
    when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
doReturn(false).when(listMock).add(anyString());
doThrow(NullPointerException.class).when(listMock).clear();

configure behavior of multiple calls 
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);

configure method to call the real, underlying method on a mock
MyList listMock = Mockito.mock(MyList.class);
when(listMock.size()).thenCallRealMethod();

assertThat(listMock.size(), equalTo(1));
configure mock method call with custom Answer
MyList listMock = Mockito.mock(MyList.class);
doAnswer(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) {
            return "Always the same";
    }
}).when(listMock).get(anyInt());

String element = listMock.get(1);
assertThat(element, is(equalTo("Always the same")));
https://gojko.net/2009/10/23/mockito-in-six-easy-examples/
  Iterator i=mock(Iterator.class);
  when(i.next()).thenReturn("Hello").thenReturn("World");
  //act
  String result=i.next()+" "+i.next();
  //assert
  assertEquals("Hello World", result);

Stubs can also return different values depending on arguments passed into the method. For example:

 when(c.compareTo(anyInt())).thenReturn(-1);

 OutputStream mock=mock(OutputStream.class);
 OutputStreamWriter osw=new OutputStreamWriter(mock);
 doThrow(new IOException()).when(mock).close();
 osw.close();


http://stackoverflow.com/questions/5981605/can-mockito-capture-arguments-of-a-method-called-multiple-times
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
https://sites.google.com/a/pintailconsultingllc.com/java/argument-matching-with-mockito
http://www.planetgeek.ch/2011/11/25/mockito-argumentmatcher-vs-argumentcaptor/
  final ArgumentCaptor<Sample> argumentCaptor =
                      ArgumentCaptor.forClass(Sample.class);
  verify(sample).setOtherSample(argumentCaptor.capture());
  assertEquals("Wrong name", "name", argumentCaptor.getValue().getName());
https://blog.frankel.ch/improve-your-tests-with-mockitos-capture
public void doneShouldPostDoneEventWithExpectedResult() {
    ArgumentCaptor<DoneEvent> captor = ArgumentCaptor.forClass(DoneEvent.class);
    EventBus eventBus = Mockito.mock(EventBus.class);
    Sample sample = new Sample(eventBus);
    sample.done();
    Mockito.verify(eventBus).post(captor.capture());
    DoneEvent event = captor.getCapture();
    assertThat(event.getResult(), is(expectedResult));
}
http://stackoverflow.com/questions/5981605/can-mockito-capture-arguments-of-a-method-called-multiple-times
verify(mockBar, times(2)).doSomething(...)
Sample from mockito javadoc:
ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());

List<Person> capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());
If you don't want to validate all the calls to doSomething(), only the last one, you can just use ArgumentCaptor.getValue(). According to the Mockito javadoc:
If the method was called multiple times then it returns the latest captured value
So this would work (assumes Foo has a method getName()):
ArgumentCaptor<Foo> fooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar, times(2)).doSomething(fooCaptor.capture());
//getValue() contains value set in second call to doSomething()
assertEquals("2nd one", fooCaptor.getValue().getName());
https://dzone.com/refcardz/mockito
Stubbing Method's Returned Value
One of the basic functions of mocking frameworks is an ability to return a given value when a specific method is called. It can be done using Mockito.when() in conjunction with thenReturn () .
thenReturn(T valueToBeReturned)Returns given value
thenThrow(Throwable toBeThrown)
thenThrow(Class<? extends Throwable>
toBeThrown)
Throws given exception
then(Answer answer)
thenAnswer(Answer answer)
Uses user-created code to
answer
thenCallRealMethod()Calls real method when working
with partial
mock/spy
Non-void methods return by default an "empty" value appropriate for its type (e.g., null, 0, false, empty collection).

Stubbing Multiple Calls to the Same Method
Sometimes you want to return different values for subsequent calls of the same method. Returned values can be mixed with exceptions. The last value/behavior is used for all following calls.

given(waterSource.getWaterPressure()).willReturn(3, 5);
assertEquals(waterSource.getWaterPressure(), 3);
assertEquals(waterSource.getWaterPressure(), 5);
assertEquals(waterSource.getWaterPressure(), 5);

Stubbing Void Methods
As we've seen before, the stubbed method is passed as a parameter to a given / when method. This obviously means that you cannot use this construct for void methods. Instead, you should use willXXX..given or doXXX..when. See here:

@Test(expectedExceptions = WaterException.class)
    public void shouldStubVoidMethod() {
    WaterSource waterSourceMock = mock(WaterSource.class);
    doThrow(WaterException.class).when(waterSourceMock).doSelfCheck();
    //the same with BDD semantics
    //willThrow(WaterException.class).given(waterSourceMock).doSelfCheck();
    waterSourceMock.doSelfCheck();
    //exception expected
}

Verifying Behavior
WaterSourcewaterSourceMock=mock(WaterSource.class);
    waterSourceMock.doSelfCheck();
    verify(waterSourceMock).doSelfCheck();
By default, Mockito checks if a given method (with given arguments) was called once and only once. This can be modified using a VerificationMode.    
times(int wantedNumberOfInvocations)called exactly n times (one by default)fl
never()never called
atLeastOnce()called at least once
atLeast(int minNumberOfInvocations)
called at least n times
atMost(int maxNumberOfInvocations)
called at most n times
only()
the only method called on a mock
timeout(int millis)
interacted in a specified time range
verify(waterSourceMock,never()).doSelfCheck();
    verify(waterSourceMock,times(2)).getWaterPressure();
    verify(waterSourceMock,atLeast(1)).getWaterTemperature();
Verifying With Argument Matching
Mockito offers an ArgumentCaptor class, enabling us to retrieve the argument passed to a mock.

//when
    flowerSearcherMock.findMatching(searchCriteria);
    //then
    ArgumentCaptor<SearchCriteria>captor=ArgumentCaptor.
    forClass(SearchCriteria.class);
    Verify(flowerSearcherMock).findMatching(captor.capture()
    );
    SearchCriteria usedSearchCriteria=captor.getValue();
    assertEquals(usedSearchCriteria.getColor(),"yellow");
    assertEquals(usedSearchCriteria.getNumberOfBuds(),3);
ArgumentCaptor can be also created using @Captor annotation

Mockito cannot:
  • mock final classes
  • mock enums
  • mock final methods
  • mock static methods
  • mock private methods
  • mock hashCode() and equals()
Nevertheless, when working with a badly written legacy code, remember that some of the mentioned limitations can be mitigated using the PowerMock or JMockit libraries.
http://www.vogella.com/tutorials/Mockito/article.html
import static org.mockito.Mockito.*;

@Test
public void testVerify()  {
  // create and configure mock
  MyClass test = Mockito.mock(MyClass.class);
  when(test.getUniqueId()).thenReturn(43);
  
  
  // call method testing on the mock with parameter 12
  test.testing(12);
  test.getUniqueId();
  test.getUniqueId();
  
  
  // now check if method testing was called with the parameter 12 
  verify(test).testing(Matchers.eq(12));
  
  // was the method called twice?
  verify(test, times(2)).getUniqueId();
  
  // other alternatives for verifiying the number of method calls for a method
  verify(mock, never()).someMethod("never called");
  verify(mock, atLeastOnce()).someMethod("called at least once");
  verify(mock, atLeast(2)).someMethod("called at least twice");
  verify(mock, times(5)).someMethod("called five times");
  verify(mock, atMost(3)).someMethod("called at most 3 times");
} 

@Spy or the spy() method can be used to wrap a real object. Every call, unless specified otherwise, is delegated to the object.

import static org.mockito.Mockito.*;

// Lets mock a LinkedList
List list = new LinkedList();
List spy = spy(list);

//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);

// this would not work
// real method is called so spy.get(0)
// throws IndexOutOfBoundsException (list is still empty)
when(spy.get(0)).thenReturn("foo");
You also have the @InjectMocks annotation which tries to do constructor, method or field dependency injection based on the type. 

@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest  {

       @Mock private ArticleCalculator calculator;
       @Mock private ArticleDatabase database;
       @Spy private UserProvider userProvider = new ConsumerUserProvider();

       // creates instance of ArticleManager
       // and performs constructor injection on it
       @InjectMocks private ArticleManager manager;

       @Test public void shouldDoSomething() {
         // assume that ArticleManager has a method called initialize which calls a method
         // addListener with an instance of ArticleListener
         manager.initialize();
         
           // validate that addListener was called
         verify(database).addListener(any(ArticleListener.class));
       }
} 

Mockito also supports the creation of mock objects based on the @Mock annotation. If you use annotations, you must initialize this mock objects with a MockitoAnnotations.initMocks(this) method call or annotate your class with the@RunWith(MockitoJUnitRunner.class) annotation to use the Mockito test runner.


Mockito has certain limitations. It can not test the following constructs:
  • final classes
  • anonymous classes
  • primitive types

import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.willDoNothing;
import static org.mockito.BDDMockito.spy;
import static org.mockito.BDDMockito.times;
(...)

@Test
public void shouldVerifyMethodExecution() {
    //given
    TacticalStation tsSpy = spy(TacticalStation.class);
    willDoNothing().given(tsSpy).fireTorpedo(2);
    //when
    tsSpy.fireTorpedo(2);
    tsSpy.fireTorpedo(2);
    //then
    then(tsSpy).should(times(2)).fireTorpedo(2);
}
Mockito methods are provided by 3 base interfaces, being an entry points for given set of methods:
– WithBDDMockito – stubbing/mocking API in BDD style (provides also classic API).
– WithMockito – classic stubbing/mocking API
– WithAdditionalMatchers – additional Mokcito matchers (basic account are included in With(BDD)Mockito)

Mockito has a feature called spy (see comment), it can be used for partiality mocking. The important thing is that you use the do-when sytnax, instead of when-then.
  • @InjectMocks - Instantiates testing object instance and tries to inject fields annotated with @Mockor @Spy into private fields of testing object
  • @Mock - Creates mock instance of the field it annotates
  • @Spy - Creates spy for instance of annotated field

14    @Test
15    public void simple_interaction_verification() {
16        // Given
17         
18        // When
19        printer.printTestPage();
20         
21        // Then
22        verify(printer).printTestPage();       
23    }
org.mockito.exceptions.base.MockitoException: This combination of annotations is not permitted on a single field: @Mock and @InjectMocks

Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);

// note that we're stubbing a chain of methods here: getBar().getName()
when(mock.getBar().getName()).thenReturn("deep");

// note that we're chaining method calls: getBar().getName()
assertEquals("deep", mock.getBar().getName());
http://googletesting.blogspot.com/2013/05/testing-on-toilet-dont-overuse-mocks.html
- Tests can be harder to understand. Instead of just a straightforward usage of your code (e.g. pass in some values to the method under test and check the return result), you need to include extra code to tell the mocks how to behave. Having this extra code detracts from the actual intent of what you’re trying to test, and very often this code is hard to understand if you're not familiar with the implementation of the production code.
- Tests can be harder to maintain. When you tell a mock how to behave, you're leaking implementation details of your code into your test. When implementation details in your production code change, you'll need to update your tests to reflect these changes. Tests should typically know little about the code's implementation, and should focus on testing the code's public interface.

- Tests can provide less assurance that your code is working properly. When you tell a mock how to behave, the only assurance you get with your tests is that your code will work if your mocks behave exactly like your real implementations. This can be very hard to guarantee, and the problem gets worse as your code changes over time, as the behavior of the real implementations is likely to get out of sync with your mocks.

Some signs that you're overusing mocks are if you're mocking out more than one or two classes, or if one of your mocks specifies how more than one or two methods should behave. If you're trying to read a test that uses mocks and find yourself mentally stepping through the code being tested in order to understand the test, then you're probably overusing mocks
Sometimes you can't use a real dependency in a test (e.g. if it's too slow or talks over the network), but there may better options than using mocks, such as a hermetic local server (e.g. a credit card server that you start up on your machine specifically for the test) or a fake implementation (e.g. an in-memory credit card server).

Invalid use of argument matchers!
3 matchers expected, 1 recorded:
This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

You cannot mock a local variable. What you could do, however, is extract its creation to a protected method and spy it:
To make this work, you need to use Powermockito to intercept the constructor calls (new InputStreamReader(...), new BufferedReader(...)) so that your mocks get returned. An example is below. In your case, just intercepting the new BufferedReader call may be enough.
You need to use something like powermock.
With powermock you create create a scenario before then method is called and play it back, this means you can tell the ArrayList class constructor to anticipate being called and return a mockrather than a real ArrayList.
This would allow you to assert on the mock.
Something like this ought to work:
ArrayList listMock = createMock(ArrayList.class);
expectNew(ArrayList.class).andReturn(listMock);
So when your method creates the local List powermock will actually return your mock List.
More information here.
This sort of mocking is really for unit testing of legacy code that wasn't written to be testable. I would strongly recommend, if you can, rewriting the code so that such complex mocking doesn't need to happen.
Personally, I have to say that PowerMock, etc. is the solution to a problem that you shouldn't have if your code wasn't bad. In some cases, it is required because frameworks, etc. use static methods that lead to code that simply cannot be tested otherwise, but if it's about YOUR code, you should always prefer refactoring instead of static mocking.
Anyway, verifing that in PowerMockito shouldn't be that hard...
PowerMockito.verifyStatic( Mockito.times(1)); // Verify that the following mock method was called exactly 1 time
SampleB.methodC();
(Of course, for this to work you must add SampleB to the @PrepareForTest annotation and call mockStatic for it.)

I tried 2.2.28 and it worked fine. I was commenting here because it was one of the top hits when I was searching for my issue and so I figured it could help other people in the future that made their way here too.

https://github.com/powermock/powermock/issues/678
https://groups.google.com/forum/#!topic/powermock/cE4T40Xa_wc
PowerMock 1.6.4 and Mockito 2: ClassNotFoundException: org.mockito.cglib.proxy.Enhancer


Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts