11

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?

1

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

It seems like PowerMock can only work with Junit4
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.