How to simulate objects created inside a method?

Consider this

public class UserManager { private final CrudService crudService; @Inject public UserManager(@Nonnull final CrudService crudService) { this.crudService = crudService; } @Nonnull public List<UserPresentation> getUsersByState(@Nonnull final String state) { return UserPresentation.getUserPresentations(new UserQueries(crudService).getUserByState(state)); } } 

I want to mock

 new UserQueries(crudService) 

so that I can mock his behavior

Any ideas?

+5
source share
2 answers

With PowerMock, you can mock designers. See example

I'm not with an IDE right now, but there will be something like this:

  UserQueries userQueries = PowerMockito.mock(UserQueries.class); PowerMockito.whenNew(UserQueries.class).withArguments(Mockito.any(CrudService.class)).thenReturn(userQueries); 

You need to run the test using PowerMockRunner (add these annotations to the test class):

 @RunWith(PowerMockRunner.class) @PrepareForTest(UserQueries .class) 

If you cannot use PowerMock, you need to enter factory as it says @Briggo's answer.

Hope this helps

+8
source

You can enter the factory that creates the UserQueries.

 public class UserManager { private final CrudService crudService; private final UserQueriesFactory queriesFactory; @Inject public UserManager(@Nonnull final CrudService crudService,UserQueriesFactory queriesFactory) { this.crudService = crudService; this.queriesFactory = queriesFactory; } @Nonnull public List<UserPresentation> getUsersByState(@Nonnull final String state) { return UserPresentation.getUserPresentations(queriesFactory.create(crudService).getUserByState(state)); } 

}

Although it might be better (if you do) to introduce CrudService in the factory.

+2
source

Source: https://habr.com/ru/post/1204489/


All Articles