Should it be “Arrange-Assert-Act-Assert”?

后端 未结 14 2549
不思量自难忘°
不思量自难忘° 2020-11-30 19:53

Regarding the classic test pattern of Arrange-Act-Assert, I frequently find myself adding a counter-assertion that precedes Act. This way I know that the passing assertion

14条回答
  •  长情又很酷
    2020-11-30 20:35

    If you really want to test everything in the example, try more tests... like:

    public void testIncludes7() throws Exception {
        Range range = new Range(0, 5);
        assertFalse(range.includes(7));
    }
    
    public void testIncludes5() throws Exception {
        Range range = new Range(0, 5);
        assertTrue(range.includes(5));
    }
    
    public void testIncludes0() throws Exception {
        Range range = new Range(0, 5);
        assertTrue(range.includes(0));
    }
    
    public void testEncompassInc7() throws Exception {
        Range range = new Range(0, 5);
        range.encompass(7);
        assertTrue(range.includes(7));
    }
    
    public void testEncompassInc5() throws Exception {
        Range range = new Range(0, 5);
        range.encompass(7);
        assertTrue(range.includes(5));
    }
    
    public void testEncompassInc0() throws Exception {
        Range range = new Range(0, 5);
        range.encompass(7);
        assertTrue(range.includes(0));
    }
    

    Because otherwise you are missing so many possibilities for error... eg after encompass, the range only inlcudes 7, etc... There are also tests for length of range (to ensure it didn't also encompass a random value), and another set of tests entirely for trying to encompass 5 in the range... what would we expect - an exception in encompass, or the range to be unaltered?

    Anyway, the point is if there are any assumptions in the act that you want to test, put them in their own test, yes?

提交回复
热议问题