Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a mock object to a class when testing?

My user class is as follows,

public class UserResource {
  @Inject UserService userService;

  public boolean createUser(User user) {
    DbResponse res = userService.addUser(user);
    if(res.isSuccess){
      return true;
    }else{
      return false;
    }
  }
}

My test class looks as follows,

public class UserResourceTest {

  UserResource userResource;

  @BeforeMethod
  void beforeMethod() {
    userResource = new UserResource();
  }

  @Test
  public void test() {
    User user= mock(User.class);
    boolean res= userResource.createUser(user);
    assert(res);
  }
}

As you can see a UserService object should be injected into the UserResource class. How can I inject a mock UserService object to userResource object inside my test?

FYI:

  • This is part of a Jersey JAX-RS project.
  • I'm using Java CDI, mockito and testNG (as the test library).
like image 230
Lasitha Yapa Avatar asked Oct 23 '25 16:10

Lasitha Yapa


1 Answers

Consider using explicit dependency principal via constructor injection as it states very clearly what is required by the class in order to perform its particular function.

public class UserResource {
  private UserService userService;

  @Inject
  public UserResource(UserService userService) {
    this.userService = userService;
  }

  public boolean createUser(User user) {
    DbResponse res = userService.addUser(user);
    if(res.isSuccess){
      return true;
    }else{
      return false;
    }
  }
}

and mock the UserService as well and assign it to the subject under test. Configure the desired/mocked behavior for the test.

public class UserResourceTest {

  @Test
  public void test() {
    //Arrange
    boolean expected = true; 
    DbResponse mockResponse = mock(DbResponse.class);
    when(mockResponse.isSuccess).thenReturn(expected);

    User user = mock(User.class);
    UserService mockService = mock(UserService.class);
    when(mockService.addUser(user)).thenReturn(mockResponse);

    UserResource userResource = new UserResource(mockService);        

    //Act
    boolean actual = userResource.createUser(user);

    //Assert
    assert(expected == actual);
  }
}
like image 178
Nkosi Avatar answered Oct 26 '25 04:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!