3
Book aBook = mock(Book.class);

when I write to execute

aBook.getClass() it gives

classcom.tw.model.Book$$EnhancerByMockitoWithCGLIB$$feb29207

But I want : classcom.tw.model.Book

Procrastinator
  • 2,526
  • 30
  • 27
  • 36
Srinivas
  • 294
  • 3
  • 18

2 Answers2

2

Since Mockito 2.1.0 you can use getMockCreationSettings() to get details on what was mocked. from the docs

Added the possibility to access the mock creation settings via

Mockito.mockingDetails(mock).getMockCreationSettings()

Here's an example:

@Test
public void aTest() {
    Foo mock = Mockito.mock(Foo.class);

    MockCreationSettings<?> mockCreationSettings = Mockito.mockingDetails(mock).getMockCreationSettings();

    Assert.assertEquals(Foo.class, mockCreationSettings.getTypeToMock());
}
Community
  • 1
  • 1
glytching
  • 44,936
  • 9
  • 114
  • 120
  • From the comments I assumed OP is calling getClass inside the method under test. This approach doesn't satisfy OPs problem then. – Absurd-Mind Sep 13 '17 at 09:31
  • The OP didn't clarify **where** he wants to call `aBook.getClass()` so I don't think it is clear yet (to me, at least :) exactly where/when/how he wants to get the original type for his mock, if he wants to get it _within_ the test case then this answer will work but if he needs to get it inside the system-under-test then it won't. – glytching Sep 13 '17 at 09:34
  • yes, you are right, I have added an answer for the other case ;) – Absurd-Mind Sep 13 '17 at 09:37
1

Use instanceof instead of getClass()

void methodUnderTest(Object object) {
    if (object instanceof Book) {
        Book book = (Book) object;
        // read the book
    }
}

this can now easily be tested with a mock:

@Test
public void bookTest() {
    methodUnderTest(mock(Book.class));
}
Absurd-Mind
  • 7,884
  • 5
  • 35
  • 47