Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...