How many unit tests should I write per function/method?

后端 未结 12 2144
忘了有多久
忘了有多久 2020-12-05 18:36

Do you write one test per function/method, with multiple checks in the test, or a test for each check?

12条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 18:46

    In Java/Eclipse/JUnit I use two source directories (src and test) with the same tree. If I have a src/com/mycompany/whatever/TestMePlease with methods worth testing (e.g. deleteAll(List stuff) throws MyException) I create a test/com/mycompany/whatever/TestMePleaseTest with methods to test differente use case/scenarios:

    @Test
    public void deleteAllWithNullInput() { ... }
    
    @Test(expect="MyException.class") // not sure about actual syntax here :-P
    public void deleteAllWithEmptyInput() { ... }
    
    @Test
    public void deleteAllWithSingleLineInput() { ... }
    
    @Test
    public void deleteAllWithMultipleLinesInput() { ... }
    

    Having different checks is simpler to handle for me.

    Nonetheless, since every test should be consistent, if I want my initial data set to stay unaltered I sometimes have, for example, to create stuff and delete it in the same check to insure every other test find the data set pristine:

    @Test
    public void insertAndDelete() { 
        assertTrue(/*stuff does not exist yet*/);
        createStuff();
        assertTrue(/*stuff does exist now*/);
        deleteStuff();
        assertTrue(/*stuff does not exist anymore*/);
    }
    

    Don't know if there are smarter ways to do that, to tell you the truth...

提交回复
热议问题