简体   繁体   English

如何在每个@Test之前运行@BeforeClass方法

[英]How to run @BeforeClass method before each @Test

When I run my @Tests manualy, one by one - everything is fine. 当我手动运行@Tests时,一个接一个-一切都很好。 But when I run them all together - I`ve got an error. 但是当我一起运行它们时-我遇到了错误。 So how can I run @BeforeClass before each @Test. 因此,如何在每个@Test之前运行@BeforeClass。 I cant use @Before becorse in my @BeforeClass I do some work in testing class constructor. 我不能在我的@BeforeClass中使用@Before becorse,我在测试类构造函数中做了一些工作。

Testing class constructor: 测试类的构造函数:

public HttpUtils() {
    this.httpClient = HttpClients.createDefault();
}

Before class: 课前:

@BeforeClass
public static void init() throws IOException {
    mockStatic(HttpClients.class);
    final CloseableHttpClient closeableHttpClient = createMock(CloseableHttpClient.class);
    when(HttpClients.createDefault()).thenReturn(closeableHttpClient);
}

If I run all test. 如果我运行所有测试。 On second test Ive got HttpClient not like mock, but like real object, and lately have error coz of it. 在第二次测试中,我得到了HttpClient,它不像模拟,而是像真实的对象,并且最近有错误提示。

Use @Before instead of @BeforeClass to execute before every test 使用@Before而不是@BeforeClass 在每次测试之前执行

@Before
public static void init() throws IOException {

with @Before causes that method to be run before the Test method. 使用@Before会使该方法在Test方法之前运行。 The @Before methods of superclasses will be run before those of the current class. 超类的@Before方法将在当前类的方法之前运行。

If you want to execute any method before each test class you should go for @Before annotation. 如果要在每个测试类之前执行任何方法,则应使用@Before注释。 By using @BeforeClass annotation you only call that method once in the test class. 通过使用@BeforeClass批注,您只需在测试类中调用该方法一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每次测试之前和之后调用@BeforeClass和@AfterClass - @BeforeClass and @AfterClass called before and after each test @BeforeClass 方法不在每个 class 之前运行 - @BeforeClass Method not runing before each class 每次测试前运行方法 - Run method before each test JUnit 4:在测试运行之前在测试套件中设置东西(比如测试的@BeforeClass方法,仅​​用于测试套件) - JUnit 4: Set up things in a test suite before tests are run (like a test's @BeforeClass method, just for a test suite) JUnit @Parameterized 函数在测试套件中的@BeforeClass 之前运行? - JUnit @Parameterized function is run before @BeforeClass in a test suite? JAVA-如何在junit的@BeforeClass方法中获取即将运行的测试模块名称 - JAVA - How to fetch the about to run test module name in @BeforeClass method of junit 如何理解@Test和@BeforeClass? - how to understand @Test & @BeforeClass? 如何在@BeforeClass测试方法调用的静态方法中使用bean - How to use bean in static method which is called by @BeforeClass test method 如何使用TestNG在循环中运行@beforeclass @test和@Afterclass案例 - How to run @beforeclass @test and @Afterclass cases in a loop using TestNG 如何在TestNG框架中的@BeforeClass方法中使用datadriven测试 - How to use datadriven test within @BeforeClass method in TestNG framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM