FMC
FMC

Reputation: 660

Ask JUnit to throw exception in method its calling

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

Upvotes: 2

Views: 2041

Answers (2)

Duncan Jones
Duncan Jones

Reputation: 69399

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();

Upvotes: 5

anand ojha
anand ojha

Reputation: 44

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.

Upvotes: -1

Related Questions