只是刚开始使用JUnit,但我无法解决此错误,这是代码段:

package ss.week2.test;

import static org.junit.Assert.*;
import ss.week2.hotel.Safe;

import org.junit.Before;
import org.junit.Test;

public class SafeTest {

@Before
public void setUp() {
    Safe safe1 = new Safe();
    Safe safe2 = new Safe();
    safe2.activate("Initial");
}

@Test
public void testSetToActiveWrong() {
    System.out.println("Testing setting to active with wrong password: ");
    assertEquals("safe1.activate(\"wrongwrong\")", true, safe1.activate("wrongwrong"));
    assertEquals("safe2.activate(\"wrongwrong\")", false, safe2.activate("wrongwrong"));
}

// Some other tests

public void runTests() {
    setUp();
    testSetToActiveWrong();
    setUp();
    testOpenWrong();
    setUp();
    testOpenRight();
    setUp();
    testDeactivate();
}

private void assertEquals(String text, boolean expected, boolean result) {
        System.out.println("        " + text);
        System.out.println("            Expected:  " + expected);
        System.out.println("            Result: " + result);
}

public static void main(String[] args) {
    System.out.println("Initial conditions: ");
    System.out.println("safe1 is closed and not active.");
    System.out.println("safe2 is closed but active.");
    new SafeTest().runTests();
}
}


调用assertEquals会给我错误:safe1无法解析
为什么是这样?我想我已经初始化了变量(没有错误),我已经导入了要测试的文件所在的包和文件(注意:Safe.java在另一个包中)。

我该如何解决?

最佳答案

safe1在您的setUp()函数中声明为局部变量。如果希望从其他方法访问它,则应将其声明为数据成员:

public class SafeTest {

    Safe safe1;
    Safe safe2;

    @Before
    public void setUp() {
        safe1 = new Safe();
        safe2 = new Safe();
        safe2.activate("Initial");
    }

    @Test
    public void testSetToActiveWrong() {
        System.out.println("Testing setting to active with wrong password: ");
        assertEquals("safe1.activate(\"wrongwrong\")", true, safe1.activate("wrongwrong"));
        assertEquals("safe2.activate(\"wrongwrong\")", false, safe2.activate("wrongwrong"));
    }

    // rest of class...

关于java - safe1无法解析(JUnit),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27077741/

10-08 23:59