daydreamer
daydreamer

Reputation: 92169

How to mock objects created inside 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 out

new UserQueries(crudService)  

so that I can mock out its behavior

Any ideas?

Upvotes: 11

Views: 30248

Answers (2)

troig
troig

Reputation: 7212

With PowerMock you can mock constructors. See example

I'm not with an IDE right now, but would 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 your test with PowerMockRunner (add these annotations to your test class):

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

If you cannot use PowerMock, you have to inject a factory, as it says @Briggo answer.

Hope it helps

Upvotes: 11

johnnyutts
johnnyutts

Reputation: 1452

You could inject a factory that creates 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 may be better (if you are going to do this) to inject your CrudService into the factory.

Upvotes: 2

Related Questions