gpt4 book ai didi

java - 如何正确实例化您在 JUnit 5 中在 before Hook 中测试的类中的对象?

转载 作者:行者123 更新时间:2023-11-28 21:21:11 26 4
gpt4 key购买 nike

@Before
public void setUp() {
Airport airport = new Airport();
}
@Test
public void has_storage(){
ArrayList<String> airport_storage;
airport_storage = new ArrayList<String>();
airport_storage.add("plane");
ArrayList<String> actual_storage = airport.storage();

我正在尝试使用 AirportTest 类测试我的机场类。与 RSpec/Jasmine 和我使用过的其他一些测试框架类似,我想确保为每个测试获得对象的新实例。尽管我已经读到实例变量在 JUnit 中无论如何都不会在测试中持续存在,所以这可能不是必需的。为什么我会收到编译器无法解析符号机场的错误?如何正确声明和初始化机场实例,使其在每个@Test 的范围内?

谢谢

最佳答案

airport 变量仅在 setUp block 中已知。如错误所述,它不知道您在谈论什么变量。

要修复它,您需要在类级别声明 airport 作为成员变量:

public class MyTest{
private Airport airport; // declare as a private class member

@Before
public void setUp() {
airport = new Airport(); // instantiate it before every test
}

@Test
public void has_storage(){
ArrayList<String> airport_storage;
airport_storage = new ArrayList<String>();
airport_storage.add("plane");
ArrayList<String> actual_storage = airport.storage(); // use it without problems
}
}

关于java - 如何正确实例化您在 JUnit 5 中在 before Hook 中测试的类中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51173620/

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