Home > Mobile >  How to set up unit test for service with dependency?
How to set up unit test for service with dependency?

Time:10-30

I have a service interface:

interface MyService
{
    int getItem();
}

and a implementation:

@Service
class MyServiceImpl : implements MyService {
    public MyServiceImpl(List<Loader> loaders) {
    }

    public int getItem() {
       Loader loader = getTheLoader();
       return loader.getItem();
    }
}

I want to unit test MyServiceImpl. There's more to it then just forwarding the getItem() call to the loader, so I'd think I'd want to test the actual class. I don't think I'd want to test an actual loader, because that would be more of an integration test, yeah?

So, I'm not sure if this is the right approach? To create a real instance of the Impl class and then create a real instance of the TestLoader?

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MyServiceTests {

    private MyService myService;

    static class TestLoader implements Loader<String, Object> {
       @Override
       int getItem() {
       }
    }

    @BeforeAll
    void init() {
        myService= new MyServiceImpl(List.of(new 
         TestLoader()));
    }

I do want to capture call counts to the TestLoader::getItem, etc.

Kinda seems like I need to create a mock loader instead of a real loader to capture the call counts?

But its not clear how I would mock a Loader<String, Object> and override the getItem() class.

CodePudding user response:

If you want to test both the class and the loader you have to do an integration test, you are right, but for unit test you have to mock other classes (that you are going to test next or you have already tested in other unit tests)

You can mock the loader (you can use mockito) and create a new list containing the mock

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MyServiceTests {

    private MyService myService;

    @Mock
    private Loader loader;

    @BeforeAll
    void init() {
        myService= new MyServiceImpl(List.of(loader));
    }
}
  • Related