1

I have a final class and want to test the catch block code through JUnit test cases. But I am not sure how can I mock the returnObject() which is being called inside the constructor, such that it throws SomeException. I used PowerMockito @Spy but in vain. I tried making the code inside returnObject() but the code is in such a manner that I cannot mock them to throw an exception. So the only option I have is to use spy the returnObject() to throw an exception.

public final class MyClass{
  public MyClass(){
    try{
      returnObject();
  }
 catch(SomeException se){
  //Logic which needs to be Junit tested
 }
}
private SomeObjectClass returnObject() throws SomeException{
   return <StaticMethodCall of another class>;
}

}

Hirein
  • 135
  • 5
  • 20
  • Did you read this thread - https://stackoverflow.com/questions/10583202/powermockito-mock-single-static-method-and-return-object ? – Dravidian Jul 06 '21 at 15:55
  • Do not mock the private method, instead pass data in that actually causes the exception. Why *does* it cause an exception in the first place? Is there not an external dependency that is called which actually causes the exception, you should mock that dependency. – luk2302 Jul 06 '21 at 16:04
  • 1
    tl;dr don't mock private things, period. They're implementation details. Test API. – chrylis -cautiouslyoptimistic- Jul 06 '21 at 16:07

0 Answers0