gpt4 book ai didi

java - @BeforeClass 和 @AfterClass 在每次测试之前和之后调用

转载 作者:行者123 更新时间:2023-12-01 17:53:54 24 4
gpt4 key购买 nike

我有一个非常简单的测试类,用于在 Android 上运行 espresso 测试,如下所示:

import android.util.Log;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.IOException;

@RunWith(JUnit4.class)
public class Wtf {

private static class TestResources extends ExternalResource {
protected void before() {
println("before() TestResources");
}
protected void after() {
println("after() TestResources");
}
}

@ClassRule
public static final TestResources res = new TestResources();

@BeforeClass
public static void setUpClass() {
println("@BeforeClass setUpClass()");
}

@AfterClass
public static void tearDownClass() throws IOException {
println("@AfterClass tearDownClass()");
}

private static void println(String string) {
Log.d("wow", Wtf.class.getSimpleName() + ": " + string);
}

@Before
public void setUp() {
this.println("@Before setUp()");
}

@After
public void tearDown() throws IOException {
this.println("@After tearDown()");
}

@Test
public void test_1() {
this.println("@Test test1()");
}

@Test
public void test_2() {
this.println("@Test test2()");
}
}

输出如下所示:

D/wow: Wtf: before() TestResources
D/wow: Wtf: @BeforeClass setUpClass()
D/wow: Wtf: @Before setUp()
D/wow: Wtf: @Test test1()
D/wow: Wtf: @After tearDown()
D/wow: Wtf: @AfterClass tearDownClass()
D/wow: Wtf: after() TestResources
D/wow: Wtf: before() TestResources
D/wow: Wtf: @BeforeClass setUpClass()
D/wow: Wtf: @Before setUp()
D/wow: Wtf: @Test test2()
D/wow: Wtf: @After tearDown()
D/wow: Wtf: @AfterClass tearDownClass()
D/wow: Wtf: after() TestResources

但我希望在整个类(class)运行后调用一些东西。难道我做错了什么?为什么每次测试之前和之后都会调用 @BeforeClass 和 @AfterClass 方法?

最佳答案

事实证明这是由于 Android Test Orchestrator :

Each test runs in its own Instrumentation instance. Therefore, if your tests share app state, most of that shared state is removed from your device's CPU or memory after each test.

我不知道解决方法,但至少现在我知道为什么会发生。

关于java - @BeforeClass 和 @AfterClass 在每次测试之前和之后调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47106147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com