代码之家  ›  专栏  ›  技术社区  ›  Ayoub k

如何使用JUnit设置全局规则

  •  0
  • Ayoub k  · 技术社区  · 6 年前

    因此,为了能够完成所有断言并在最后列出失败的断言,我使用了 ErrorCollector @Rule 注释。
    下面是一个测试类的示例:

    public class MovieResponseTest {
    
        /**
         * Enable a test not to stop on an error by doing all assertions and listing the failed ones at the end.
         * the <code>@Rule</code> annotation offers a generic way to add extended features on a test method
         */
        @Rule
        public ErrorCollector collector = new ErrorCollector();
    
    
        /**
         * A test case for <code>setCelebrity</code> Method
         * @see MovieResponse#setCelebrities(List)
         */
        @Test
        public void testSetCelebrities() {
            // Some code
    
            this.collector.checkThat("The size of cast list should be 1.", this.movieResponse.getCast(), hasSize(1));
            this.collector.checkThat("The size of directors list should be 1.", this.movieResponse.getDirectors(), hasSize(1));
            this.collector.checkThat("The size of writers list should be 1.", this.movieResponse.getWriters(), hasSize(1));
        }
    }
    

    @规则 将军,所以我不用写了 public ErrorCollector collector = new ErrorCollector(); 在每个测试班。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Ekrem Demirhan    6 年前

    创建一个抽象类,将ErrorCollector放入其中,并使所有测试类扩展这个抽象类。

    public abstract class UnitTestErrorController {
        // Abstract class which has the rule.
        @Rule
        public ErrorCollector collector = new ErrorCollector();
    
    }
    
    public class CelebrityTest extends UnitTestErrorController {
        // Whenever a failed test takes places, ErrorCollector handle it.
    }
    
    public class NormalPeopleTest extends UnitTestErrorController {
        // Whenever a failed test takes places, ErrorCollector handle it.
    }
    
        2
  •  0
  •   thenamethatwasnottaken    6 年前

    为什么不把“测试集名人”分成多个测试呢?类似于“directorsHasProperSize”、“writersaspropersize”等。如果您的测试与所提供的示例相似,那么您似乎在使用ErrorCollector来减少您的测试数量和/或使它们的名称与所测试的方法相似。这是不必要的,而且对你不利,因为你不必要地增加了测试的复杂性,而且你的语句比常规断言更难阅读。