Reputation: 727
I have a use case where I'm trying to ensure that an abstract exception is thrown when a particular method is called in my class.
I am using Mockito to do this, but have noticed that Mockito is simply not throwing an exception when the method is being called.
Class to be tested:
public void doSomething() throws CustomException {
try {
Collection<T> results = dao.getDatabaseResults();
} catch (ProblemException e) {
throw new CustomException("There was an exception", e);
}
}
Problem Exception class:
public abstract class ProblemException extends RuntimeException {
public ProblemException(String message) {
super(message);
}
public ProblemException(String message, Throwable e) {
super(message, e);
}
Test Class:
public testDoSomething() throws Exception {
CustomDAO mockDAO = Mockito.mock(CustomDAO.class);
Mockito.when(mockDAO.getDatabaseResults()).thenThrow(new ProblemException);
try {
foo.doSomething();
Assert.fail();
} catch (CustomException e) {
//Some more asserts
}
Currently the above test class won't compile because you can't create a new instance of an abstract class.
I do not have the access to change the AbstractException class and I also cannot change the exception type that is thrown by the getDatabaseResults() method on the DAO class.
Do you have any suggestions on the cleanest solution for this problem?
One thing I can think of is to catch a RuntimeException within my doSomething() method (as ProblemException extends this class). I was just curious if there are any better ways?
Thanks
Upvotes: 4
Views: 7751
Reputation: 41145
You can't instantiate an abstract class directly, but you can easily instantiate an anonymous subclass, and that's pretty trivial in this case as you're not forced to define any methods:
Mockito.when(mockDAO.getDatabaseResults()).thenThrow(new ProblemException(){});
Alternatively, you can just use another mock:
Mockito.when(mockDAO.getDatabaseResults()).thenThrow(Mockito.mock(ProblemException.class));
This would make sense if the abstract class forced the definition of other methods you don't care about in your test.
Upvotes: 17