Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking the class type of a mock object

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.

Thank you very much for the help.

Best Regards

Gerardo

like image 276
Gerardo Avatar asked Jun 07 '11 12:06

Gerardo


4 Answers

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()));
like image 113
millhouse Avatar answered Nov 09 '22 19:11

millhouse


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();
like image 35
z7sg Ѫ Avatar answered Nov 09 '22 19:11

z7sg Ѫ


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));
like image 20
Adam Avatar answered Nov 09 '22 19:11

Adam


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.

like image 44
mamboking Avatar answered Nov 09 '22 19:11

mamboking