Giedrius
Giedrius

Reputation: 139

Mockito - how to unit test if argument is set in a function called by another function

I have two classes.

My service is calling cleanup() function which then calls function from repository repository.insertSomething(something)

I need to test if insertSomething has set it's property after the cleanup() has been called.

I have started my test code like this

Service mock = mock(Service.class);
ArgumentCaptor<Repository> argument = ArgumentCaptor.forClass(Repository.class);
verify(mock).cleanup(); <-- have no access to the arguments of the child function and can't use the captor.

As given in example I have no access to the function that is called inside the scope of the cleanup function.

How do i get access to test the arguments of the function which is called by another function.

PS.

I can't call the repository function directly since it loads its argument from a configuration file. And the test should execute given that the cleanup function has been called.

// Child method
@Query("insert into .... where ?1 < ....")
void insertSomething(LocalDate date);

Upvotes: 2

Views: 1966

Answers (1)

Dmitrii B
Dmitrii B

Reputation: 2860

You have some service that you want to test. There are some inner dependencies and you want to check their calls. For the typical service's unit test you usually should mock all of the inner dependencies and their behaviors like that:

class ServiceTest {

@Mock
private Repository repository;

@InjectMocks
private Service service;

@BeforeEach
void setUp(){
  initMocks(this);
}

@Test
void serviseTest(){
   SomeReturnType retVal = mock(SomeReturnType.class);

   when(repository.call(any())).thenReturn(retVal);

   service.call(any);

   verify(repository).call(any());
   verifyNoMoreInteractions(repository);
  }
}

This generics code can be an example of your problem's solution.

Upvotes: 4

Related Questions