这是我的A级考试中-

class A extends ServerResource {
    @Override
    protected void doInit() throws ResourceException {
    }

    @Get
    public String getUsers() {
        String userJson = null;
        // want to mock
        UserFacade userFacade = new UserFacade();
        // database call: want to return resources
        List<Resource> resources = userFacade.getDrUsersByExample();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        userJson = gson.toJson(resources);
        return userJson ;
    }

}


这是测试课程-

@RunWith(MockitoJUnitRunner.class)
class ATest {
    @Mock
    UserFacade userFacade;

    List<Resource> resources;

    @Before
    public void setUp() throws Exception {
      Resource resource = new Resource();
      resource.setName("user");
      resource.setTask("manual");
      resources.add(resource);
    }

    @Test
    public void testUsers() {
      when(userFacade.getDrUsersByExample()).thenReturn(resources);

      A a = new A();

      // causes NullPointerException for userFacade.getDrUsersByExample()
      String userList = a.getUsers();
    }

}


为什么即使使用when(userFacade.getDrUsersByExample()).thenReturn(resources)后,我仍会为模拟对象获取NullPointerException?

最佳答案

需要将模拟的UserFacade明确注入到测试对象中。当前,由于方法内部的Anew UserFacade()与该依赖关系紧密耦合。

紧密耦合被认为是代码异味且设计不良。重构类以遵循显式依赖原则。

class A extends ServerResource {
    UserFacade userFacade;

    public A(UserFacade userFacade) {
        this.userFacade = userFacade;
    }

    @Override
    protected void doInit() throws ResourceException {
    }

    @Get
    public String getUsers() {
        String userJson = null;
        // database call: want to return resources
        List<Resource> resources = userFacade.getDrUsersByExample();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        userJson = gson.toJson(resources);
        return userJson ;
    }
}


然后将需要更新测试以完成测试。

@Test
public void testUsers() {
    //Arrange
    when(userFacade.getDrUsersByExample()).thenReturn(resources);

    A a = new A(userFacade);

    //Act
    String userList = a.getUsers();

    //Assert
    //...
}

07-27 13:23