3

The task is to cause NoSuchMethodException exception when calling table.annotationType().getMethod("name").

I have following code

@Mock(answer = RETURNS_DEEP_STUBS)
private Table table;

@Test(expectedExceptions = NoSuchMethodException.class)
public void testGetSupportClassesDatabaseThrowException() throws NoSuchMethodException {
    String testPackageName = "com.usc.dbd.util.supporttable";

    MockitoAnnotations.initMocks(this);

    when(table.annotationType().getMethod("name")).thenThrow(NoSuchMethodException.class);

    SupportTables.getSupportClasses(testPackageName);
}

The test fails with NullPointerException on when... line.

testCompile("org.mockito:mockito-core:2.7.17")

Table is annotation from javax.persistence

Probably the issue is in mocking Table interface.

I'm looking for solution how to test such case.

  • Would it be possible for you to share you complete set of dependencies? I would like to try and figure out what is causing the `NullPointerException` but I havent been able to narrow down on the dependencies properly. – Krishnan Mahadevan May 04 '18 at 04:03
  • Possible duplicate of [Mockito - NullpointerException when stubbing Method](https://stackoverflow.com/questions/33124153/mockito-nullpointerexception-when-stubbing-method) – Pavneet_Singh Aug 31 '18 at 17:40

1 Answers1

1

Two things here:

  • the NPE is strange ( will see if I can find an explanation later on )
  • even without an NPE, your test is pointless

You see, you create one mocked instance of the Table class. That you configure to react to a certain call with an exception.

Then you call a static method, without using that mocked object in any way. That simply will not do anything.

That later, static call doesn't know anything about your mocked table instance. You probably assume that your mock setup will affect any Table object. No, it will not! It only affects calls that happen on that specific object.

If you want to control any arbitrary instance of Table, created anywhere, you have way more things to do (for example you would have to look into using PowerMock or JMockit to intercept/control constructor calls).

Long story short: as written right now, your test case doesn't at all do what you wrote it for.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Starting with a question, this seems to be a comment, not an answer. – Turing85 May 02 '18 at 14:05
  • mockito version 2.7.17; `Table` is annotation from `javax.persistence`; `annotationType()` is method from `java.lang.annotation`. – Oleksandr Stefanovskyi May 02 '18 at 14:06
  • @Turing85 Not necessarily. And if that helps: with more information from the OP, I could rewrite it without a question mark. Well, still a question mark regarding the NPE ... – GhostCat May 02 '18 at 14:20
  • @AStefanovskiy See my updates. In short: I think your whole test is bogus. Even without that NPE, it wouldnt do what you think it should do. – GhostCat May 02 '18 at 14:20