【问题标题】:interesting null pointer exception at grails testgrails测试中有趣的空指针异常
【发布时间】:2011-03-01 12:02:26
【问题描述】:

我想为我的 grails 应用程序编写单元测试。

但是groovy中null对象模式存在问题。

我使用 for 创建一个实例:

KeywordClickPerformance performance = KeywordClickPerformance.forA("string").from(startDate).to(endDate)

但是当这样使用时;

void testForA() {
    assertEquals "string", performance.keyword.name
}

在单元测试执行之后,grails 给出了这个异常:

"java.lang.NullPointerException: Cannot get property 'name' on null object at "

我使用performance?.keyword?.name 作为解决方案,但它返回null,因为performancenull

我没有找到解决方案。我该如何解决这个问题?

【问题讨论】:

  • 当性能为空时,我无法完全理解您还在等待什么其他值?
  • 我期望 KeywordClickPerformance 提供一个字符串,但性能可能不为空

标签: unit-testing grails groovy nullpointerexception


【解决方案1】:

您需要在测试或设置中创造性能。否则你的 forA 方法不对...

【讨论】:

  • 我们使用 KeywordClickPerformance performance = KeywordClickPerformance.forA("string").... 在 forA 方法中性能为 null,这已经是问题所在了。
【解决方案2】:

未创建性能。您需要在 = 右侧的 KeyworkClickPerformance 前面添加新的。我认为 groovy 将允许链接构造函数。如果没有,你可以分两行完成

KeywordClickPerformance 性能 = new KeywordClickPerformance() performance.forA("string").from(startDate).to(endDate)

【讨论】:

  • 好的,我试过了,但没有正确的解决方案。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
相关资源
最近更新 更多