1

我正在为 Singleton 类编写测试用例。但是调用将转到原始依赖项。
模拟注入不适用于数学和艺术。

    private final Math math;
    private final Art art;
    private final tot;

    private Student(Math math, Art art){
        this.math = math;
        this.art = art;
    }
    public static Student getInstance() {
        Student st= new Student(new Mant(), new Art());
        st.display();
        return st;
    }

    public void display() {
         tot = math.getScore() + art.getScore();
    }
}

测试班

public class StudentTest{
    @Test
    @PrepareForTest(Student.class)
    void testDisplay() {
        Math mockMath = PowerMockito.mock(Math.class);
        PowerMockito.when(mockMath.getScore()).thenReturn(80);
        Math mockArt = PowerMockito.mock(Art.class);
        PowerMockito.when(mockArt.getScore()).thenReturn(70);
        Student mst= Student.getInstance();
        mst.display();
        assertEquals(mst.tot(), 150);
    }
}
4

1 回答 1

1

@RunWith(PowerMockRunner.class)注释添加到您的测试类

@RunWith(PowerMockRunner.class)
public class StudentTest{
    @Test
    @PrepareForTest(Student.class)
    void testDisplay() {
        Math mockMath = PowerMockito.mock(Math.class);
        PowerMockito.when(mockMath.getScore()).thenReturn(80);
        Math mockArt = PowerMockito.mock(Art.class);
        PowerMockito.when(mockArt.getScore()).thenReturn(70);
        Student mst= Student.getInstance();
        mst.display();
        assertEquals(mst.tot(), 150);
    }
}
于 2020-04-13T13:19:44.073 回答