编写多个测试函数会为除第一个以外的每个案例给出 NullPointerException

Writing multiple test functions gives NullPointerException for each case except the first

我正在尝试测试 VideoStore Class 的功能,它包含一个名为 store 的视频类型数组。当我 运行 测试 class 作为 junit 测试时,只有 4 个测试中的第一个通过,其他的抛出 NullPointer 异常。当我 运行 单独测试时,每个测试都通过了。我已完成测试 class.

我已经尝试使用@BeforeClass 代替@Before 注解。 我也试过在 east @Test 函数中单独实例化。

import static org.junit.Assert.*;

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

import tm2.VideoStore;

public class VideoTest {
VideoStore vs;

@Before
public void before() {
    vs = new VideoStore();
    vs.addVideo("LifeOfGuy");
}

@Test
public void testAddVideo() {
    assertEquals("LifeOfGuy",vs.store[0].videoName);
}

@Test
public void testDoCheckout() {
    vs.doCheckout(vs.store[0].videoName);
    assertTrue(vs.store[0].checkout);
}

@Test
public void testDoReturn() {
    vs.doReturn("LifeOfGuy");
    assertFalse(vs.store[0].checkout);
}

@Test
public void receiveRating() {
    vs.receiveRating("LifeOfGuy", 5);
    assertEquals(5,vs.store[0].rating);
}
}

VideoStore Class:

public class VideoStore {

public Video[] store = new Video[10];
static int count = 0;

public void addVideo(String name) {
    store[count++] = new Video(name);
}

public void doCheckout(String name) {
    for(int i=0; i<count; i++) {
        if((store[i].videoName).equals(name)) {
            store[i].doCheckout();
            break;
        }
    }
}

public void doReturn(String name) {
    for(int i=0; i<count; i++) {
        if((store[i].videoName).equals(name)) {
            store[i].doReturn();
            break;
        }
    }
}

public void receiveRating(String name, int rating) {
    for(int i=0; i<count; i++) {
        if((store[i].getName()).equals(name)) {
            store[i].receiveRating(rating);
        }
    }
}

void listInventory() {
    System.out.println("----------------------------------------");
    System.out.println("Video Name | Checkout Status | Rating ");
    for(int i=0; i<count; i++) {
        System.out.println(store[i].videoName+"  |  "+store[i].getCheckout()+"  |  "+store[i].getRating());;
    }
    System.out.println("----------------------------------------");
}
}

Junit 结果:---- 运行 4/4 错误 3 失败 0 1.testAddVideo通过 2. testDoCheckout java.lang.NullPointerException 3. 测试返回 java.lang.NullPointerException 4. testreceiveRating java.lang.NullPointerException

每一个单独通过

您的 count 变量是静态的,因此它会随着每次测试而增加,并且新视频会添加到数组中的不同位置以进行每次测试

成功non-static

private int count = 0;