Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: Verify a boolean method (or other types)

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 ;)

like image 309
BAERUS Avatar asked May 11 '15 09:05

BAERUS


1 Answers

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!
    }
}
like image 50
BretC Avatar answered Oct 05 '22 21:10

BretC