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();
}
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:
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,
Stringis part of thejava.langpackage, 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 thejava.*package). But this is just an assumption from my side.