JUnit:无法解析 obj

问题描述

我使用 JUnit 4 编写了一个小型 Java 程序。我编写了两种方法,一种带有 @Before 注释,另一种带有 @Test。 我创建了一个obj 的对象,但它说 obj 无法解析。

@Before
public void objectCreation() {
    Main obj = new Main(msg);
}

@Test
public void testPrintMessage() {      
   assertTrue("Expected true got false",obj.printMessage());
}

解决方法

objobjectCreation 方法中的局部变量。您应该将其声明为成员,并且仅在该方法中对其进行初始化:

public class JunitDemo {
    private static final String msg = "Hello world";
    Main obj;

    @Before
    public void objectCreation() {
        obj = new Main(msg);
    }

    @Test
    public void testPrintMessage() {      
       assertTrue("Expected true got false",obj.printMessage());
    }

}