-1

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.

caesar
  • 11
  • 1
  • 5
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Raju Dangol Sep 14 '17 at 04:50
  • Possibly because `def DataSource dataSource` means your datasource is `null`. Try instantiating or mocking it as well – Naman Sep 14 '17 at 04:50
  • I have tried that by changing "def DataSource dataSource" to "DataSource dataSource=Mock() " but still Null Pointer Exception is coming. – caesar Sep 14 '17 at 05:06
  • You create `table` as a mock, but you never pass it on to your `comparison` instance. Furthermore, `1*table.fetchData(_ as DataSource)` needs to return at least an empty map or `records.size()` will throw an NPE as well. – Leonard Brünings Sep 16 '17 at 17:25

2 Answers2

0

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>

CommodoreBeard
  • 340
  • 2
  • 12
-1

The reason may be the variable of records is null, you should mock for records.