user2856064
user2856064

Reputation: 553

Return expected list of values in test

This is a dummy code with the test (junit5+mockito). How to enforce to return expected list of values in the unit test? I try with spy(), mock(), but I don't get expected value or sometimes I get null pointer exception.

class A {
}

public interface B {
    public List<A> f1();
}

class X {
    B o1;
    public X(B y) {
        o1 = y;
    }

    protected void x() {
        List<A> results = m1();
        // ...
    }
    protected List<A> m1() {
        return o1.f1();
    }
}

class XTest {
    @Mock
    private static B b;

    @BeforeAll
    public static void setUp() {
        b = org.mockito.Mockito.mock(B.class);
    }

    @Test
    public void t1() {
        X s = spy(new X(b));

        A p = new A();
        A r = new A();
        List<A> c = Arrays.asList(p, r);
        when(s.m1()).thenReturn(c);         // how to enforce m1() to return c ?
    }
}

Upvotes: 0

Views: 562

Answers (2)

rmunge
rmunge

Reputation: 4248

You test class X and for this you mock class B. Never mock the class that you want to test:

class XTest {

    private static B b;

    @BeforeAll
    public static void setUp() {
        b = org.mockito.Mockito.mock(B.class);
    }

    @Test
    public void t1() {
        X s = new X(b);

        A p = new A();
        A r = new A();
        List<A> c = Arrays.asList(p, r);
        when(b.f1()).thenReturn(c);         //  m1() calls f1 and returns c 
    }
}

Upvotes: 1

0xh3xa
0xh3xa

Reputation: 4857

Try to use doReturn, like this:

public class XTest {

    @Mock
    private B b;

    @Test
    public void t1() {
        X s = spy(new X(b));
        List<A> list = Arrays.asList(new A(), new A());
        doReturn(list).when(s).m1();

        //
        doSomething
    }
}

Upvotes: 1

Related Questions