Karate Mocks on Google CloudRun

I have written mock features in Karate for integration testing. Recently I wanted to run them centrally somewhere so all my testing infra can use the same set of Mocks. I wanted an easy way to launch it and maintenance-free. So I tried it with CloudRun, which can run any stateless web service. One needs to provide a container to it. That's all.

It works like any FAAS. It can scale down to zero when not used. And can scale up as much as you want.

Dockerfile

# Dockerfile
# Use official openjdk
# https://hub.docker.com/_/openjdk
FROM adoptopenjdk/openjdk11:alpine-slim

COPY . ./

CMD exec java -jar /karate-1.0.0.jar -m mock.feature -p $PORT

ClourRun always starts the service on $PORT port. Hence use it in your Dockerfile.

mock.feature

Feature: stateless mock server

Background:
* def cats = {}

Scenario: pathMatches('/greeting') && paramExists('name')
    * def content = 'Hello ' + paramValue('name') + '!'
    * def response = { content: '#(content)' }

Scenario:
    * print request
    * def response = { content: "Welcome"}    

build.sh

For building the container

# build.sh
gcloud config configurations activate [configuration_name]
gcloud config set project [project_name]
gcloud config set run/region asia-south1
gcloud builds submit --tag gcr.io/[project_name]/karate-mock-app

deploy.sh

Deploy container to CloudRun

gcloud config configurations activate [configuration_name]
gcloud config set project [project_name]
gcloud config set run/region asia-south1
gcloud run deploy karate-mock-app --allow-unauthenticated --platform managed --image gcr.io/[project_name]/karate-mock-app

You will have to replace [configuration_name] and [project_name] in the above scripts with appropriate value.

Note

I have not tried to use stateful mock service as CloudRun is stateless and can lose memory. The mock I wanted was stateless, so it didn't matter much.

I also found a weird /bin/sh error when running java on cloudrun when I used WORKDIR and tried to launch java from WORKDIR. Hence I moved it to root directory. It worked fine afterward.

ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./