【问题标题】:Unit Testing Null Pointer Exception单元测试空指针异常
【发布时间】:2016-02-05 12:39:27
【问题描述】:

我目前正在尝试完成一项测试驱动开发课程,但遇到了以下代码的问题:

package stockInformation;

public class StockInformation {

String companyName;

public String getCompanyName() {
    return companyName;
}

private WebService webService;

// Constructor
public StockInformation(int userID) {

    if (webService.authenticate(userID)){
        //Do nothing
    } else {
        companyName = "Not Allowed";
    }
}
}

(if-else 故意做得不好,以便我以后可以在作业中对其进行重构)

“正在由另一个团队开发”的 Web 服务,因此需要进行模拟 打包库存信息;

public interface WebService {

public boolean authenticate(int userID);

}

测试类

package stockInformation;

import org.junit.Before;
import org.junit.Test;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

public class StockInformationTest {

WebService mockWebService;
StockInformation si;

@Before
public void setUp() throws Exception {
    mockWebService = createMock(WebService.class);
}

@Test
public void testUserIdAuthentication() {
    int userID = -2;
    si = new StockInformation(userID);
    expect(mockWebService.authenticate(userID)).andReturn(false);
    replay(mockWebService);
    assertEquals("Not Allowed", si.getCompanyName());
    verify(mockWebService); 
}

}

当我运行单元测试时,我在以下位置收到 NullPonterException:

if (webService.authenticate(userID)){

si = new StockInformation(userID);

我希望单元测试通过 :) 任何帮助表示赞赏。

【问题讨论】:

  • 你对代码运行时webService 的值有理论吗?您认为该值是多少?
  • webService 只是表示将具有方法 authenticate(int userId) 的接口,该方法根据给定的 userId 是否满足验证返回 true 或 false。 WebService 接口中不应编写任何实际功能,因此在单元测试中使用 andReturn。
  • 我明白这一点。 认为webService在代码运行时有什么价值?
  • webService 被声明为 WebService 类型的值。 falseWebService 类型的有效值吗?
  • 深入了解 :)

标签: unit-testing tdd easymock


【解决方案1】:

您永远不会在 StockInformation 类中设置 private WebService webservice。在StockInformation 构造函数中使用它,它的值为null。

【讨论】:

    【解决方案2】:

    您应该以某种方式为 StockInformation 类的 webService 字段分配一个值。

    这可以通过反射或setter方法来完成:

    public void setWebService(WebService webService) {
        this.webService = webService;
    }
    

    然后在测试执行期间,您将模拟 WebService 实例设置为 StockInformation 实例:

    si = new StockInformation(userID);
    si.setWebService(mockWebService);
    

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2018-08-27
      • 1970-01-01
      • 2017-11-17
      • 2021-10-13
      相关资源
      最近更新 更多