Crazywolf
Crazywolf

Reputation: 41

Using PowerMockito to mock interface implementations

I need to mock an call that implements an interface in my code

public interface User {
    public void getUser(User userId, Role role);
}

public UserService implements User {

   public void UserService(User userId, Role role) {

   }
}

Another service class :

public ValidationService {

    public void validateUser() {
        ***User user = new UserService(user,role);***

   }
}

I wanted to mock UserService / User using Powermockito or mock, how to do this?

I followed this approach:

@RunWith(PowerMockRunner.class)
@PrepareForTest({UserService.class,User.class})
public class ValidationServiceTest {
    @Mock
    User user = Mockito.mock(User.class);

    @Test
    public void getValidUser() {
        PowerMockito.whenNew(UserService.class).withAnyArguments().thenReturn(user); 
    }
}

This doesn't seem to work, how would I mock the interface?

Upvotes: 0

Views: 1347

Answers (1)

glytching
glytching

Reputation: 47905

Inject a User into the ValidationService rather than creating it inside the ValidationService. For example:

public ValidationService {

    private User user;

    public ValidationService(User user) {
        this.user = user;
    }

    public void validateUser() {
        // use the 'user' class member...
   }
}

Now, mocking User becomes simple:

User user = Mockito.mock(User.class);

ValidationService sut = new ValidationService(user);

// establish any test-specific expectations of the User instance here

sut.validateUser();

There's no need for PowerMock here, just plain old Mockito and dependency injection.

Note: Dependency injection doesn't require the use of Spring or Guice or whatever. Those libraries are just a means of implementing DI. Manually constructing your objects by passing in their dependent classes (via constructor or setters) is another way of implementing DI. The key point here is that adopting this approach will allow you to inject a different implementation of User when you construct a ValidationService for use by your test case.

Upvotes: 1

Related Questions