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

前端 未结 12 2014
广开言路
广开言路 2020-12-12 08:53

I have written a few JUnit tests with @Test annotation. If my test method throws a checked exception and if I want to assert the message along with the exceptio

12条回答
  •  不思量自难忘°
    2020-12-12 09:16

    Do you have to use @Test(expected=SomeException.class)? When we have to assert the actual message of the exception, this is what we do.

    @Test
    public void myTestMethod()
    {
      try
      {
        final Integer employeeId = null;
        new Employee(employeeId);
        fail("Should have thrown SomeException but did not!");
      }
      catch( final SomeException e )
      {
        final String msg = "Employee ID is null";
        assertEquals(msg, e.getMessage());
      }
    }
    

提交回复
热议问题