Error while executing Integration Test with JSON o

2019-08-03 19:12发布

Below is my action in the controller. I am trying to test this action via an integration test. This would require me to mock the session objects as well. I have started with the integration test, but have no luck with it.

def listData= {

    def playerId=session["playerId”]    

    tuneInstanceList = tuneService.calculateId(playerId)


    def listResult = [total: tuneInstanceList.size(), items: tuneInstanceList]

    render listResult as JSON;

}

Below is the CalculateId method in my service class:

List<Tune> calculateId(String playerId) {              

   try{ 
   //read the sql file  
        String playerSql = grailsApplication.mainContext.getResource('classpath:'     +         Constants.PLAYER_FILE).inputStream.text  

def sql = new groovy.sql.Sql(dataSource)                  

def params = [playerId:playerId]  
def tuneInstanceList = new ArrayList<Tune>()  

def results = sql.rows(playerSql, params)  

tuneInstanceList = results.each {  
    def tune = new Tune()  
    tune.setPlayerId  it.player_id    
    tuneInstanceList.add tune 
} 
return tuneInstanceList 

 }catch (Exception ex) { 
    log.error ex.message, ex 
    throw ex 
} 
//finally { 
    //sql.close() 
//} 

}

Below is the Integration Test that I wrote. This isn’t correct and I am not sure what I should be putting up here. Inputs?

    public void testQuery () {

    def myController = new TuneController()
    myController.request.contentType = "text/json"

    myController.tuneService = tuneService

    myController.listData()

    String actualJSON = myController.response.contentAsString

    assertNotNull(actualJSON)




}

I get the below error when I run the test.

Cannot get property 'request' on null object

java.lang.NullPointerException: Cannot get property 'request' on null object

Thoughts??

1条回答
在下西门庆
2楼-- · 2019-08-03 19:42

Worked out the Test Case for this scenario.Below is the code. Thanks!

public void testJSONQuery () {   
  def tuneController = new TuneController()
  tuneController.request.contentType = "text/csv"
  tuneController.tuneService = tuneService  
  tuneController.session["playerId"]='AF67H'    
  tuneController.listData()
  String tuneJSON = tuneController.response.contentAsString

  log.info ('Number of Records on execution of query is' + tuneJSON.substring(9,10))


 //Checks if the record count is greater than zero
  assertTrue (new Integer(tuneJSON.substring(9,10)).intValue() > 0)

}
查看更多
登录 后发表回答