Mockito验证未失败 [英] Mockito Verification Not Failing

查看:81
本文介绍了Mockito验证未失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使Mockito中的verify方法起作用.我有以下测试:

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

该测试应该失败,但是可以通过.有人知道为什么吗?我使用Mockito错了吗?

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

更新

这是另一个没有失败的例子:

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

推荐答案

好吧,您应该注意这一点:默认情况下,您不能模拟最终课程(例如String). 这是框架的已知限制.

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

因此,我想您的项目中可能存在一些较小的配置问题.您正在使用哪个IDE?您有哪个版本的Mockito?您如何运行测试?

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?

您可以尝试使用其他一些工具包,例如 PowerMock ,它可以帮助您

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.

另一方面,Stringjava.lang程序包的一部分,我假设VM还对这些类进行了其他一些安全性验证(虽然不确定).我不认为您可以模拟(即操作字节码)此类(例如,如果尝试将某些内容放入java.*包中,则会出现编译错误).但这只是我的一个假设.

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.

这篇关于Mockito验证未失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆