How to avoid multiple asserts in a JUnit test?

前端 未结 7 778
故里飘歌
故里飘歌 2020-11-29 12:12

I have a DTO which I\'m populating from the request object, and the request object has many fields. I want to write a test to check if the populateDTO() method

7条回答
  •  半阙折子戏
    2020-11-29 12:39

    Is that rule extended to being in a loop? Consider this

    Collection expectedValues = // populate expected values
    populateDTO();
    for(DTO dto : myDtoContainer) 
      assert_equal(dto, expectedValues.get(someIndexRelatedToDto))
    

    Now I'm not so big on the exact syntax, but this is just the notion I'm looking at.

    EDIT: After the comments...

    The answer is ... Nope!

    The reason the principle exists is so you can identify which parts of the object fail. If you have them in one method, you're going to run into only one assertion, then the next, then the next, and you won't see them all.

    So you can have it one of two ways:

    1. One method, less boilerplate code.
    2. Many methods, better reporting on the test run

    It's up to you, both have ups and downs. 3. List item

提交回复
热议问题