Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

java - Null Pointer Exception in Unit test in spock

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

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

When I run it I get

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

why is that so.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok so a couple of points I can see:

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

  • Static: DataSource dataSource
  • Dynamic: def 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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...