6

I know that you can only verify void methods. But I actually ask myself why.

I recently stumbled upon an unit test where I really need to verify that a certain call has been made. To be exact, it's "newFolder.mkdirs()". The behavior of this method is pretty much "voidy" in my opinion. But as a "feature" the devs provided this function a boolean return type to see whether the action was successful or not.

Nice, but I don't care much for that in my test where I throw my mocks around. I just want to ensure that this very call was done, just like I would want to ensure that important void calls were done.

So is there now a possibility to do that? I'm quite stuck on this, can't even imagine a workaround for that tiny problem :/ Somebody got a good, short idea?


I was totally wrong: You can verify everything. I misplaced the brackets.

I had:

verify(newFolder.mkdirs());

I needed:

verify(newFolder).mkdirs();

Silly me ;)

BAERUS
  • 4,009
  • 3
  • 24
  • 39
  • I am not sure what issue are you facing? You mean you want to try something like: `when(mock.hasNextItem()).thenAnswer(new Answer() { Object answer(InvocationOnMock invocation) { called = true; return item; }` Here the method `hasNextItem()` returns `boolean`. – akhil_mittal May 11 '15 at 09:17

1 Answers1

2

I may have misunderstood, but where does it say that you can only verify void methods?

For example...

import org.junit.Test;
import static org.mockito.Mockito.*;

public class VoidTest {

    private interface TestClass {
        boolean doStuff(String arg);
    }

    @Test
    public void doIt() {
        TestClass tc = mock(TestClass.class);

        tc.doStuff("[SOMETHING]");

        verify(tc).doStuff("[SOMETHING]"); // OK
        verify(tc).doStuff("[SOMETHING ELSE ]"); // BOOM!
    }
}
BretC
  • 4,141
  • 13
  • 22
  • Damn you are right, or rather I was completely wrong. What I accedently did was "verify(newFolder.mkdirs());" instead of "verify(newFolder).mkdirs();" --> Misplaced brackets :( – BAERUS May 11 '15 at 09:24