1

I have a Controller class with something like this

public void create(int a, int b){
     //do something
}

Now i want to mock the Controller class and call a certain method for exmaple doCustomCreate() when the create Method of my mocked Controller class is called.

My test would ´look something like this

Controller ctrlMock = mock(Controller.class);
//PseudoCode: when(isCalled(ctrlMock.create(a,b)).doCall(doCustomCreate());

I only read about mocking methods with input and return values, so i wondered if this is possible?

Edit: Updated the Question

Gobliins
  • 3,848
  • 16
  • 67
  • 122
  • 1
    The list is a private field of the mocked object. Why do you care about what it contains? It seems you want the mock to do what it would do if it was not mocked. – JB Nizet Jan 05 '15 at 12:56
  • google "mockito void method", first result – Joeblade Jan 05 '15 at 12:56
  • @JBNizet actually technically it's a package level protected. Thoguh I doubt it's actually used as such in the authors code. – Joeblade Jan 05 '15 at 12:58
  • It seems that you are trying to use a mock for a different purpose than what it's really intended for. Please could you explain a bit more what you want to test? – Ray Jan 05 '15 at 13:01
  • @Ray Why so? I use Mockito for the exact purpose as Mockito was designed. – Gobliins Jan 05 '15 at 13:18
  • i updated the question maybe it is now a bit more clear – Gobliins Jan 05 '15 at 13:38
  • @Gobliins i think @Ray means you might want to consider using a `stub`, not a `mock`. [this](http://stackoverflow.com/a/17810004/3380951) explains the difference. – XoXo Jan 05 '15 at 22:50

2 Answers2

5

Just use this API for void methods :

doAnswer(doCustomCreate()).when(ctrlMock).create(a,b);

Or with BDDMockito :

willAnswer(doCustomCreate()).given(ctrlMock).create(a,b);

Where doCustomCreate() returns an Answer (that returns null). Note I used Void just to indicate this answer don't return anything.

public Answer<Void> doCustomCreate() {
    return new Answer<Void>() {
        public Void answer(InvocationOnMock invocation) {
            // your stuff
            return null;
        }
    }
}

Note giving behavior to a mock is somehow a rocky path for maintainability of tests, as it means the tested component is not tested in pure controlled environment / isolation.

bric3
  • 40,072
  • 9
  • 91
  • 111
0

So you want to override the mock's behavior for a certain method. The solution for this is using a so-called spy (AKA partial mock) instead of a mock: http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#16

Ray
  • 3,084
  • 2
  • 19
  • 27
  • No, this is the opposite of what i want to do.I don't want to call the real method, for what would i need a mock then? i want to call my own method. If you would replace the 'when(mock.someMethod()).thenCallRealMethod();' by 'when(mock.someMethod()).thenCallMyCustomMethod();' then it would be logical. – Gobliins Jan 05 '15 at 14:21