Checking the class type of the mock object

I am currently testing a method that receives an object and checks to see if this object is an instance of a class that is stored as an instance variable. Not a problem yet.

But in the test I have to use mocks, and one of these mocks is the object that is passed to this method. And now it's getting complicated. Let's look at the code (I summarized 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 anyone have an idea how I can solve this problem while still using the layout, as in the test? Is there any other way to compare objects with a specific class.

Thank you for help.

Best wishes

Gerardo

+9
instanceof mockito mocking
source share
5 answers

Your first statement will never be true - Mockito mocks is a completely new class, so simple equals() will never work. By the way, for such tests you will get a much more useful error message if you use Assert.assertEquals() , where the first argument is the expected result; eg:.

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

Your second statement would be correct, but you mixed the direction of isAssignableFrom() (easy to do, JavaDoc is very confusing) - flip it and you are golden:

 Assert.assertTrue(clazz.isAssignableFrom(adapterEvent.getClass())); 
+8
source share

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

 Assert.assertTrue(adapterEvent instanceof AdapterEvent); 

Are you sure you need to even check this? Not knowing that you are trying to do this is hard to say, but I think this test might not be needed.

+2
source share

Mockito 2.0.0 introduces a new getMockedType method that returns the class originally passed to Mockito.mock(Class) . I would recommend using this method because the getSuperClass() method does not work in all cases.

 MockingDetails mockingDetails = Mockito.mockingDetails(mockObj); Class<?> cls = mockingDetails.getMockedType(); 
+2
source share

To verify that the object returned an instance of the class in C # that you expect, do the following

 Assert.IsInstanceOfType(adapterEvent, typeof(AdapterEvent)); 
+1
source share

The Mocked class is subclassed from your source class, so just check the superclass, for example:

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

0
source share

All Articles