Dmytro
Dmytro

Reputation: 2009

Test methods invocation with Mockito

I use Spring in my DAO and Service layer. Now i trying to test this layers with Mockito framework. What i want is just to check that appropriate method was called.

This is my configuration where i mocks all required dependencies:

@Configuration
public class MockConfig
{
    @Bean
    public EntityManagerFactory entityManagerFactory()
    {
        return mock(EntityManagerFactory.class);
    }

    @Bean
    public BaseRepositoryImpl baseRepositoryImpl()
    {
        return mock(BaseRepositoryImpl.class);
    }

    @Bean
    public BaseServiceImpl baseServiceImpl()
    {
        return mock(BaseServiceImpl.class);
    }
}

And this is how i trying to test this:

@ContextConfiguration(classes = MockConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseServiceTest
{
    @Autowired
    private BaseService<Entity> service;

    @Autowired
    private BaseRepository<Entity> repository;

    @Test
    public void testSave()
    {
        Entity entity = new Entity("testId", "testName");
        service.save(entity);

        verify(service).save(entity);

        //try to test that Service calls appropriate method on Repository
        verify(repository).save(entity);
    }

But test fails on Repository mock. I want to ensure that Service calls appropriate method, and then its Repository(that is @Autowired in Service) calls appropriate method in turn. But seems that i misunderstood something about mocks. If anyone know how this can be accomplished please help. Thanks in advance.

Upvotes: 0

Views: 782

Answers (1)

beerbajay
beerbajay

Reputation: 20270

You shouldn't be mocking your service in this case. Your service is the object under test; you need an actual instance of it.

@Configuration
@ComponentScan(basePackages = {"my.package.service"})
public class MockConfig {
    @Bean
    public BaseRepositoryImpl baseRepositoryImpl() {
        return mock(BaseRepositoryImpl.class);
    }
}

Then in your test:

@Autowired
@InjectMocks
private BaseService<Entity> service;

Finally, remove verify(service).save(entity);

Upvotes: 1

Related Questions