简体   繁体   中英

@BeforeEach not affect the Test, and the object not initialized - Eclipse with JUNIT

I have created a simple project with Eclipse which uses JUNIT 5.

The Account Object should initialized well, before each test, but actually the method doesn't recognize the object and return null exception in the test.

I have tried solution from other questions.

All my imports look fine. And at the run configuration it's defined to use jUnit 5.

What is the problem ? Thanks

The test:

package account;

import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;

class AccountTest {
    Account account;

    @BeforeEach
    void setUp() {
        Account account = new Account();
        System.out.println("Hi" + account.owner);
    }
    
    @Test  
    void assertBeforeEachWorking() {

        System.out.println("Befroe each? ");
        System.out.println(account.owner);
//      assertEquals("default owner2", account2.owner, "owner name not right" );
    }

}

Account:

package account;

public class Account {
    
    int amount ;
    String owner = "default owner";

}

运行配置

测试结果

As @Rob Spoor pointed at the comment, I was mistakenly creating a local variable at the method.

changing to:

@BeforeEach
    void setUp() {
        account = new Account();
        System.out.println("Hi" + account.owner);
        
    }

Have solved the problem.

I leave this question for maybe in the future this mistake will happen to others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM