【发布时间】:2018-04-25 15:03:57
【问题描述】:
我正在尝试使用 setUp 为我的测试方法在 JUnit 中初始化一个对象数组,但是我做错了,因为测试引发了错误(空指针异常)。当我在测试方法本身中初始化数组时,它们运行良好,但这显然并不理想。谁能指出我在这里做错了什么?
class MainTest {
Lord baratheons[];
Lord starks[];
//Setup & Teardown
@Before
static void setUp() throws Exception {
Lord baratheons[] = new Lord[3];
baratheons[0] = new Lord("Robert", 15);
baratheons[1] = new Lord("Renly", -5);
baratheons[2] = new Lord("Stannis", 30);
System.out.println("Baratheons initialised!");
Lord starks[] = new Lord[3];
starks[0] = new Lord("Robb", -60);
starks[1] = new Lord("Eddard", 0);
starks[2] = new Lord("Jon", 90);
System.out.println("Starks initialised!");
}
//Tests
@Test
void testGratefulLord() {
// Lord baratheons[] = new Lord[3];
// baratheons[0] = new Lord("Robert", 15);
int x = baratheons[0].getRelationship();
baratheons[0].giveFief();
assertEquals(baratheons[0].getRelationship(), (x+=10));
}
编辑:
注意 除了遵循以下解决方案中概述的步骤外,我还想为后人指出,我也使用了错误的标签进行设置。因为这是 JUnit 5,所以标签是 @BeforeEach。 @Before 是 JUnit 4 的标签,这就是没有调用 setup 方法的原因。我希望这对未来的用户有所帮助。
【问题讨论】:
-
这是一个范围问题。您在 setUp() 中声明了一个与全局数组同名的数组。只需执行
baratheons = new Lord[3];就可以了 -
此外,为了获得良好的编码风格,您应该将数组括号放在类之后,而不是变量名。所以请改用
Lord[] baratheons -
就像在
setUp()?这可以防止int x = baratheons[0].getRelationship();无法将baratheon解析为变量。 -
除非您删除了全局声明,否则它应该不会无法解析。保留它,只需在 setUp() 中将行更改为
baratheons = new Lord[3];和starks = new Lord[3]; -
然后从
setUp方法中删除static。