簡體   English   中英

未在 JUnit 中調用 setUp()

[英]setUp() not being called in JUnit

出於某種原因,我的測試類的 setUp() 方法沒有在我的測試方法之前被調用。

import static org.junit.jupiter.api.Assertions.*;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.Test;

class BlockchainAuctionTest {
    private BlockchainAuction auction;

@Before
public void setUp() {
    auction = new BlockchainAuction();
    System.out.println("setUp");
}

@After
public void tearDown() {
    System.out.println("tearDown");
}

@Test
void testOneBid() {
    Bid bid = new Bid("Bitcoin", "Devon", 1.0);
    assertTrue(auction.recordNewBid(bid), "first bid should be added without error");
}
}

具體來說,我在行上收到一個空指針異常

assertTrue(auction.recordNewBid(bid), "first bid should be added without error");

因為拍賣還沒有初始化。 我正在使用 Eclipse。

您使用的是 JUnit 5 @Test但 JUnit 4 @Before / @After

您需要使用來自org.junit.jupiter @BeforeEach / @AfterEach

從它的外觀來看,您可以嘗試更改導入

import org.junit.jupiter.api.Test;

import org.junit.Test;

好吧,對我來說,這就是它的工作方式。 我用過了:

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


它奏效了。 我也用過

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


它也起作用了。 任何其他組合對我都不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM