Reputation:
I need to test a constructor which throws an exception using JUnit.
Below is the constructor:
public EISThirdPartyClient(ClientConfiguration _config, String _serviceURL)
throws EISClientException {
super(_config, _serviceURL);
try {
ObjectMapperHolder.initialize(_config);
} catch (Exception e) {
throw new EISClientException(e);
}
}
Below is the test case:
@Test
public void testEISThirdPartyClientConctructor() throws EISClientException {
@SuppressWarnings("unused")
EISThirdPartyClient client = new EISThirdPartyClient(new ClientConfiguration(), "url");
boolean caughtException = false;
try {
ObjectMapperHolder.initialize(null);
} catch (Exception ex) {
if (ex instanceof EISClientException) {
caughtException = true;
assertTrue(ex.getCause() instanceof EISClientException);
} else {
ex.printStackTrace();
fail("Uncaught exception");
}
}
assertTrue(caughtException);
}
I am getting java.lang.AssertionError
, which isn't what I'm expecting. Can someone tell me what I am doing wrong?
Upvotes: 0
Views: 89
Reputation: 106498
You're testing the wrong thing - you want to ensure that the construction of your object fails, not that it bails out when ObjectMapperHolder
bails out.
You can also greatly simplify the test - you can expect that EISClientException
is thrown without needing to do any further validation of the exception.
The main point is to get the test to fail with the minimum required amount of work. It seems that passing null
as your configuration might do it, so here's an example with that:
@Test(expected = EISClientException.class)
public void testEISThirdPartyClientConctructor() throws EISClientException {
new EISThirdPartyClient(null, "url");
}
If this doesn't quite suit your needs, you may want to look into a mocking framework like Mockito to provide behavior when you are in the critical section of your code.
Upvotes: 2