7

I'll begin with a code example; I have to test a function, which handles data-packets. In this function, the data-packet is opened and when it doesn't contain all expected data, an InvalidParameterExeption is thrown which is logged.

public void handleData(dataPacket) { try { analyseData(dataPacket); } catch (InvalidParameterException e) { e.printStackTrace() } } 

So, if everything goes well, my exception is printed in my terminal. But how can I test this? I can't use this: (because the exception is caught)

@Test(expected = InvalidParameterExeption.class) public void testIfFaultyDataPacketIsRecognised { handleData(faultyDataPacket); } 

How can I test that the InvalidParameterExeption is thrown?

3
  • Either you shouldn't catch the exception or you should remove the @expected annotation and figure out something else to asset. Printing a stack trace isn't handling an exception very well. The fact that you're confused about what to do is a hint of how clients of your class feel when there's a bad data packet and they have no idea what to do. Commented Nov 18, 2016 at 12:15
  • Write a test for analyseData instead of handleData. Commented Nov 18, 2016 at 12:16
  • 1
    What if a method analyseData is private? Commented Nov 17, 2021 at 14:03

2 Answers 2

8

You won't catch exceptions that are not thrown. Just test the 'throwing exception' method instead of the 'exception catching' one

@Test(expected = InvalidParameterExeption.class) public void testIfFaultyDataPacketIsRecognised() { analyseData(faultyDataPacket); } 
Sign up to request clarification or add additional context in comments.

3 Comments

I had this test already. But I was testing on a higher level of abstraction and checking if I could make my system crash by sending all kinds of data. These tests were in fact double checking, but it is not necessary.
What did you mean by throwins exception method?
if analyseData method is private how would call it? So you have to call handleData method which in turn calls this method. In this case you cannot use above logic.
0

Ideally you should catch and rethrow the exception.But if you dont want to do that then Why not get catch the exception in test case as expected?

@Test public void testIfFaultyDataPacketIsRecognised () { try { handleData(faultyDataPacket); Assert.fail("Fail! Method was expected to throw an exception because faulty data packet was sent.") } catch (InvalidParameterException e) { // expected } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.