在一个项目中,有多个测试类,每个测试类包含多个测试方法.比如,我想在运行每个测试类之前创建数据库连接.无论我是运行单个测试类,多个测试类还是测试套件,都应该建立连接.
最重要的是,在多个测试类的情况下,不应该反复调用此步骤.无论我正在运行的测试类的数量如何,都应该只进行一次连接.
最重要的是,在多个测试类的情况下,不应该反复调用此步骤.无论我正在运行的测试类的数量如何,都应该只进行一次连接.
你能否提出一个设计或任何JUnit技巧来解决这个问题?
解决方法
您可以在测试套件中运行这些类.请参阅
this question和提供的答案.
或者更改您的设计并使用@BeforeClass
注释在每个测试类之前运行一次安装.
Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests,sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.