Forum Discussion

PrathapR's avatar
PrathapR
Frequent Contributor
5 days ago

How to read mock service responses from files

Hi All,

Have a mock service which expects multiple responses depending on the request path parameter (ex: emp id). For this thought to store responses in a folder at project level as JSON files (Ex: 123456.json). 

I did setup mock service in ReadyAPI, when I'm running this project on local (EX: http://localhost:8080/...) it's working fine with expected responses. But when I run this mock service on a virtual server (by drag and drop to server, http://svrt12345.com:8080/....) it's not reading response files. Not getting any error (getting 200 OK) but empty response.

I tried to keep those test data files in Vert server (svrt123456.com:8080) at same location path where my local has (EX: D:/ReadyAPI/Project1/TestData/12345.json).

API Request: /Countries/US/City/NYC/State/NY/EmpId/12345/EmpS/M/EmpSummary
TestDataFile Path:  ProjectDir/TestData/12345.json (12346.json, 12347.json..)
ReadyAPI Version: 3.54.0

Used below script. I tried keeping this script multiple places like OnRequest script or Response Script or Script Dispatch Style but none of them worked.

import groovy.json.JsonSlurper
import java.nio.file.Files
import java.nio.file.Paths
import  com.eviware.soapui.support.*

// Get the request path
def requestPath = mockRequest.getPath()

// Extract path parameters from the request path
def pathSegments = requestPath.tokenize('/')

def empId = pathSegments[7]

// Access the project object
def projectDir = new File(context.mockService.project.path).getParent()

// 2. Define the folder path relative to the project directoryr
def testDataDirectory = new File(projectDir, 'TestData')

// 3. Construct the full path of the JSON file based on the parameter
def jsonFile = new File(testDataDirectory, "${empId}.json")

// 4. Check if the file exists
if (jsonFile.exists()) {
    // 5. Read the file content and return it as the Mock Response
    def jsonContent = jsonFile.text
	
 // 6. Set the JSON content to the mock response
	//  mockResponse.responseContent = jsonContent;
 context.response = jsonContent;

}else {
   // 7. Log an error and return an error response if the file doesn't exist
    log.error("File not found for Route: ${empId}")

}

 

 

 

If anyone has done this before or knowledge, please share your thoughts. TIA.

No RepliesBe the first to reply