1

Is there a way I can tell a JUnit to enter a method and throw an exception so that I can test error handling scenarios?

Thanks

FMC
  • 650
  • 12
  • 31

2 Answers2

3

No, not in the way you describe it. A typical solution would be to mock the object in question and instruct the mock to throw an exception when the method is invoked.

Take a look at Mockito, which is a popular framework for mocking in Java. The code would be essentially:

doThrow(new SomeException()).when(yourMockedObject).yourMethod();
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
-1

I think this would be helpful: How do you assert that a certain exception is thrown in JUnit 4 tests?

You will have to simulate those exception scenarios as well.

Community
  • 1
  • 1
anand ojha
  • 44
  • 3