1

I made a small Java program using JUnit 4. I wrote two methods, one with a @Before annotation and one with @Test. I created an object of a class obj but it says obj can't be resolved.

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

@Test
public void testPrintMessage() {      
   assertTrue("Expected true got false",obj.printMessage());
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    Please read https://meta.stackoverflow.com/q/285551 – Alex May 17 '21 at 10:07
  • 2
    1. Please post code, not images. 2. Learn about scope of variables in Java: https://www.baeldung.com/java-variable-scope – Lesiak May 17 '21 at 10:10

1 Answers1

1

obj is a local variable in your objectCreation method. You should declare it as a member, and only initialize it in that method:

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());
    }

}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Note that unless the `Main(String)` constructor declares that it throws a checked exception, there is no need to use `@Before` in the test. You can simply assign "obj" at declaration time: `private final Main obj = new Main(msg)` – NamshubWriter Jul 28 '21 at 03:18