Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito Verification Not Failing

I'm trying to get the verify method in Mockito to work. I have the following test:

@Test
public void testShouldFail()
{
    String string = mock(String.class);
    string.length();
    verify(string, times(100)).length();
}

This test should fail, but it passes. Does anybody know why? Am I using Mockito wrong?

Update

Here's another example that doesn't fail:

private interface Bar
{
    public void foo();
}

@Test
public void testShouldFail()
{
    Bar bar = mock(Bar.class);
    bar.foo();
    verify(bar, times(100)).foo();
}
like image 217
LandonSchropp Avatar asked Mar 04 '12 08:03

LandonSchropp


1 Answers

Well, you should be careful about that: by default, you cannot mock final classes (like String). This is a known limitation of the framework.

Your example fails for me with the proper error message:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.lang.String
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types
    at Test.testShouldFail(Test.java:6)
         ...

So I guess there might be some minor configuration problems in your project. Which IDE are you using? Which version of Mockito do you have? How do you run your tests?

You might try using some additional toolkit like PowerMock which helps you overcome this limitation. This framework can be used in conjuction with Mockito quite easily.

On the other hand, String is part of the java.lang package, and I assume there are some additional security verifications involved of those classes by the VM (ain't sure though). I'm not convinced that you can mock (i.e., manipulate the bytecode) of such a class (for instance, you get a compilation error if you try to put something in the java.* package). But this is just an assumption from my side.

like image 183
rlegendi Avatar answered Sep 28 '22 08:09

rlegendi