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

前端 未结 2 1382
無奈伤痛
無奈伤痛 2021-01-14 19:11

My user class is as follows,

public class UserResource {
  @Inject UserService userService;

  public boolean createUser(User user) {
    DbResponse res          


        
2条回答
  •  抹茶落季
    2021-01-14 19:18

    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);
      }
    }
    

提交回复
热议问题