Drex
Drex

Reputation: 3851

Java - Mockito - how to inject depency into abstract in test

I have an abstract class where in the constructor there is an inject service, how could I mockup both abostract class and inject service in unit test, here is the code example

public abstract class SomeService {
    private final SomeClient someClient;

    @Inject
    public SomeService(SomeClient someClient) {
        this.someClient = someClient;
    }

    public User myMethod(int uid) {
        User user = someClient.getUserByUid(uid);
        ...
        return user;
    }

Here is what I want to mockup and test my method

public class SomeServiceTest {
   @Mock
   private SomeService someService;

   @Mock
   private SomeClient someClient;

   @Before
    public void Setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        // here how could I inject my someClient into my someService
        when(someClient.getUserByUid(anyInt).Return(mockedUserObj); 
    }

   @Test
   public void myMethodTest(int uid) {
         User result = someService.myMethod(1);
          //here I want to mock up a response from my someClient that would be equal to mockedUserObj, but the someClient here doesn't seem to be the instance of someService
    }
}

How could I inject my someClient into my someService of both mocked up class? so that I can mock up the inner method call response using the same mocked up client instance here?

Upvotes: 1

Views: 73

Answers (1)

Erik Karlstrand
Erik Karlstrand

Reputation: 1537

Seeing as abstract classes cannot be instantiated it would make sense to create a concrete subclass just for testing purposes.

public class MockSomeService extends SomeService {

}

public class SomeServiceTest {

    @Mock 
    private SomeClient someClient;

    private MockSomeService mockSomeService;

    @Before
    public void setUp() {

        MockitoAnnotations.initMocks(this);
        mockSomeService = new MockSomeService(someClient);
        when(someClient.getUserByUid(Matchers.anyInt()).thenReturn(mockedUserObj);
    }

    @Test
    public void myMethodTest(int uid) {

        // Do stuff
    }
}

Upvotes: 1

Related Questions