开发者

Checking the class type of a mock object

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 c开发者_开发问答ode (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 know 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.


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

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


I would think that instanceof would work the way you want it to:

Assert.assertTrue(adapterEvent instanceof AdapterEvent);

Are you sure you should even be testing for this? Not knowing what you're trying to accomplish it's hard to say but I think this test might not be necessary.


There is a new method getMockedType in Mockito 2.0.0 that returns the class originally passed into Mockito.mock(Class). I would recommend using this method because the getSuperClass() technique doesn't work in all cases.

MockingDetails mockingDetails = Mockito.mockingDetails(mockObj);
Class<?> cls = mockingDetails.getMockedType();


To test an object has returned the instance of a class in C# you are expecting then do the following

Assert.IsInstanceOfType(adapterEvent, typeof(AdapterEvent));


The Mocked class is subclassed from your original class, so just check the superclass, like this:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜