In Java, setup() and @Before are used together 在测试方法之前执行一些准备工作
. Setup() is a method in JUnit. It is usually used to initialize test objects and set up the test environment . It will be called before each test method is executed. , and objects and environments can be shared among multiple test methods . @Before
is an annotation in JUnit, it 用于标记一个方法
. 在每个测试方法执行之前被自动调用
By using the @Before annotation, we can place some common preparation operations (such as creating objects, initializing variables, etc.) in a method 避免在每个测试方法中重复编写相同的准备代码
. By doing this 同时使用setup()和@Before
, we can perform some shared initialization and preparation work before the test method and ensure that this work will be performed in each test method. so可以提高代码的重用性和可维护性,并减少重复代码的编写。
package JunitTest;
import org.junit.Before;
import org.junit.Test;
public class ExampleTest {
@Before
public void setup() {
// 在每个测试方法执行之前执行的代码
System.out.println("执行setup()方法");
}
@Test
public void test1() {
// 测试方法1
System.out.println("执行测试方法1");
}
@Test
public void test2() {
// 测试方法2
System.out.println("执行测试方法2");
}
}
Output:
执行setup()方法
执行测试方法1
执行setup()方法
执行测试方法2