Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to invoke mocked object's method?

I have, for example, this class:

public class A {
    private List<String> list;

    public A(B b){
        list = b.getList();
    }

    public List<String> someMethod(){
        return list;
    }
}

I want to unit test someMethod without invoking constructor. I use reflection to set list.

The problem is that I don't want to create B class object and I cannot mock it since it will cause NPE.

So my question is:

How to test someMethod without calling constructor of A? Is there any way to mock class A and doesn't lose posibility to call methods?

Creating constructor with zero arguments is not a solution.

Note: I don't want to change any part of A class. I'm asking if it is possible to perform this test without adding or changing anything in A class.

like image 647
nervosol Avatar asked Jun 17 '26 22:06

nervosol


1 Answers

You can test class A without calling it's constructor by Mockito. Not sure if I really understand your requirement but the following codes work for me.

import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ATest {

    @Test
    public void test() {
        A a = mock(A.class);
        when(a.someMethod()).thenCallRealMethod();
        List<String> listInA = new ArrayList<String>();
        ReflectionTestUtils.setField(a, "list", listInA);
        assertThat(a.someMethod(), is(listInA));
    }
}
like image 72
Tatera Avatar answered Jun 20 '26 13:06

Tatera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!