chad
chad

Reputation: 11

Parameterized Singleton class test

I am writing test case for Singleton class. But call is going to original dependency.
Mock injection is not working for Math and Art.

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

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

Upvotes: 1

Views: 59

Answers (1)

deadshot
deadshot

Reputation: 9061

Add the @RunWith(PowerMockRunner.class) annotation to your test 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);
    }
}

Upvotes: 1

Related Questions