spock单元测试中的空指针异常 [英] Null Pointer Exception in Unit test in spock

查看:71
本文介绍了spock单元测试中的空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ComparisonService"类,具有以下 fn-

i Have a class "ComparisonService" with the following fn-

public HashMap <String, Map<String, Object>> fetchTableData(DataSource dataSource, List<Object> tableInfo){
    table.setTableInfo(tableInfo);
    HashMap<String, Map<String, Object>> records = table.fetchData(dataSource);
    System.out.println(records.size());
    return records;
}

这里的表是其他类表的对象

Here table is an Object of other class Table

我正在为此方法编写 spock 测试-

I am writing a spock test for this Method-

class ComparisonSpec extends spock.lang.Specification{
Table table=Mock()
def DataSource dataSource
def List<Object> tableInfo=[1]
def setup()
{
    //def DataSource dataSource 
}
def "first function"()
{
    given:
    def ComparisonService comparison= new ComparisonService()
    when:
    comparison.fetchTableData(dataSource,tableInfo)
    then:
    1*table.setTableInfo(_ as String)>>true
    1*table.fetchData(_ as DataSource)
}

当我运行它时,我得到

空指针异常在compare.fetchTableData(dataSource,tableInfo).

null pointer Exception at comparison.fetchTableData(dataSource,tableInfo).

为什么会这样.

推荐答案

好的,我可以看到几点:

Ok so a couple of points I can see:

第一 def DataSource dataSource您正在尝试静态和动态键入变量.这应该是:

First def DataSource dataSource You are trying to statically and dynamically type your variable. This should be either:

  • 静态:DataSource dataSource
  • 动态:def dataSource

第二个您声明变量 dataSource 但从未初始化它.无论是在测试中还是在您需要的设置中:dataSource = <数据源是什么>

Second You declare the variable dataSource but never initialise it. Either in the test or the setup you need: dataSource = <what ever data source is>

这篇关于spock单元测试中的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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