检查模拟对象的类类型 [英] Checking the class type of a mock object

查看:74
本文介绍了检查模拟对象的类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在测试获取对象的方法,并检查该对象是否是作为实例变量存储的类的实例.到目前为止没有问题.

currently I'm testing a method that gets an object and checks if that object is an instance of a class that is stored as instance variable. So far no problem.

但是在测试中,我必须使用模拟,这些模拟之一是传递给该方法的对象.而现在,它变得棘手.让我们看一下代码(我在此测试中总结了代码):

But in the test I have to use mocks and one of these mocks is the object that is passed on to that method. And now, it becomes tricky. Let's see the code (I summed up the code in this test):

    Class<AdapterEvent> clazz = AdapterEvent.class;
    AdapterEvent adapterEvent = Mockito.mock(AdapterEvent.class);

    Assert.assertTrue(adapterEvent.getClass().equals(clazz));
    Assert.assertTrue(adapterEvent.getClass().isAssignableFrom(clazz));

嗯,这个测试实际上失败了.有谁知道为什么吗?有人知道我仍然可以通过在测试中使用模拟来解决这个问题吗?可能还有另一种将对象与特定类进行比较的方法.

Well, this test actually fails. Does anyone knows why? Does somebody has an idea how I could solve this problem by still using a mock like in the test? Is there maybe another way of comparing objects to a specific class.

非常感谢您的帮助.

最好的问候

杰拉多

推荐答案

您的第一个断言永远不会成立-Mockito模拟是一个全新的类,因此简单的equals()将永远无法工作.顺便说一下,对于像这样的测试,如果使用Assert.assertEquals(),您将获得更多有用的失败消息,其中第一个参数是预期的结果.例如:

Your first assertion will never be true - Mockito mocks are a whole new class, so a simple equals() will never work. By the way, for tests like this you'll get a far more useful failure message if you use Assert.assertEquals(), where the first argument is the expected result; e.g.:

Assert.assertEquals(clazz, adapterEvent.getClass()); 

您的第二个断言将是是正确的,但是您混淆了isAssignableFrom()的方向(轻松实现,JavaDoc令人困惑)-将其翻转即可,您很高兴:

Your second assertion would be correct, but you've mixed up the direction of isAssignableFrom() (easily done, the JavaDoc is mighty confusing) - flip it around and you're golden:

Assert.assertTrue(clazz.isAssignableFrom(adapterEvent.getClass()));

这篇关于检查模拟对象的类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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