测试时如何将模拟对象注入类? [英] How to inject a mock object to a class when testing?

查看:445
本文介绍了测试时如何将模拟对象注入类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户类别如下,

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

如您所见,应该将UserService对象注入到UserResource类中.如何在测试中将模拟的UserService对象注入到userResource对象?

仅供参考:

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:

  • 这是Jersey JAX-RS项目的一部分.
  • 我正在使用Java CDI,mockito和testNG(作为测试库).

推荐答案

考虑通过构造函数注入使用显式依赖项主体,因为它非常清楚地声明了类执行其特定功能所需的条件.

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

并模拟UserService并将其分配给被测对象.配置测试所需的/模拟的行为.

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

这篇关于测试时如何将模拟对象注入类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆