How do I use Assert.Throws to assert the type of the exception?

Assert.Throws returns the exception that’s thrown which lets you assert on the exception. var ex = Assert.Throws<Exception>(() => user.MakeUserActive()); Assert.That(ex.Message, Is.EqualTo(“Actual exception message”)); So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert.Throws assertion will fail. However if an exception of the correct type is thrown then … Read more

How do I assert my exception message with JUnit Test annotation?

You could use the @Rule annotation with ExpectedException, like this: @Rule public ExpectedException expectedEx = ExpectedException.none(); @Test public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() throws Exception { expectedEx.expect(RuntimeException.class); expectedEx.expectMessage(“Employee ID is null”); // do something that should throw the exception… System.out.println(“=======Starting Exception process=======”); throw new NullPointerException(“Employee ID is null”); } Note that the example in the ExpectedException docs is … Read more

Best practice for using assert?

Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state. Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes. For example, if you’re writing a function to read from … Read more