How to get an output from JUnit assertEquals() method and put it into a variable?

前端 未结 2 1842
南旧
南旧 2021-01-22 08:11

I have a JUnit test case here to test a simple class. Basically the class contains just one method called \'sum\' that returns the sum of two numbers. To test if this is right I

相关标签:
2条回答
  • 2021-01-22 08:20

    From the Java doc assertEquals will

    Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null, they are considered equal.

    You have to catch AssertionError when your condition fails.

    Try this code:

     @Test
        public void myTest() throws Exception{
            String assertionError = null;
            try {
                Assert.assertEquals(2,3);
            }
            catch (AssertionError ae) {
                assertionError = ae.toString();
            }
            System.out.println(assertionError);
    
        }
    

    OUTPUT:

    java.lang.AssertionError: expected:<2> but was:<3>

    For more info about AssertionError visit java doc : AssertionError and Assert

    0 讨论(0)
  • 2021-01-22 08:40

    assertEquals is a void method. You cannot put the result to variable. But you can get the exception with try/catch block.

    try{
      assertEquals("foo", "foo1"); //will fail
    } catch(AssertionError e){
      String message = e.getMessage();
      //do whatever you want with e
    }
    
    0 讨论(0)
提交回复
热议问题