简体   繁体   中英

Should assert be placed in the test case or verification method?

For regression testing (not unit testing), where we have elaborate scenarios written in TestNG, is there a proper place the Assert checks should be done? Does it matter or not if it's in the test case, or in a calling method? For example:

This test case calls a validation method that contains the asserts:

@Test
public void test1() {
    validateResponse();
}

public void validateResponse() {
    Assert.assertEquals(a, "123");
    Assert.assertEquals(b, "455");
    Assert.assertEquals(c, "5678");
    Assert.assertEquals(d, "3333");
}

This test case asserts based on the return value of the verification method:

@Test
public void test1() {
    Assert.assertTrue(validateResponse());
}

public boolean void validateResponse() throws Exception {
    try {
        if (!a.equals("123")) throw new Exception();
        if (!b.equals("455")) throw new Exception();
        if (!c.equals("5678")) throw new Exception();
        if (!d.equals("3333")) throw new Exception();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

Your assert should be as specific and granular as possible to help the developer quickly identify the problem. eg

@Test 
public void testResponseFields(){
    // create response to be tested

    // JUnit style
    Assert.assertEquals("Response 'alpha' should be '123'", 123, response.getAlpha());

    // TestNG style
    Assert.assertEquals(response.getAlpha(), 123, "Response 'alpha' should be '123'");
}

Once you set a failure message in the Assert.assertXX call, it becomes more of a moot point as to where the Assert is called as you will have a message explaining the problem and a stack trace to see where and when it failed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM