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.

2

1 Answer 1

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.

4
  • Starting with a question, this seems to be a comment, not an answer.
    – Turing85
    Commented May 2, 2018 at 14:05
  • mockito version 2.7.17; Table is annotation from javax.persistence; annotationType() is method from java.lang.annotation. Commented May 2, 2018 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
    Commented May 2, 2018 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
    Commented May 2, 2018 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.