0

Is one better than the other? if so, for what reasons? I am leaning towards the first because i can understand what the test is trying to much more quickly.

If so, when should one be using assertThrows()?

@Test(expected=CustomException.class)
public void test_one() {
   execute()
}

vs.

@Test
public void test_one() {
    assertThrows(CustomException.class, () -> execute());
}

1 Answer 1

3

Lets say you have your test this way:

@Test
public void test_one() {
   execute1();
   execute2()
}

Assume you want to check CustomException thrown by execute2().

Now if you go with the first approach, and execute1() throws the CustomException test will still pass and you won't be able to know whether it was thrown by execute2() or not.

But with the second approach you can specify that you want to make sure that exception is thrown by execute2() method call, hence test will only pass when the CustomException is thrown by execute2() method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.