Wednesday 5 February 2014

Low ceremony http request mocking with Betamax

Whilst researching effective http request mocking in junit tests I came across a great project called Betamax created by Rob Fletcher.
Betamax is a tool for mocking external HTTP resources such as web services and RESTAPIs in your tests. The project was inspired by the VCR library for Ruby. 
You don’t want 3rd party downtime, network issues or resource constraints (such as the Twitter API’s rate limit) to break your tests. Writing custom stub web server code and configuring the application to connect to a different URI when under test is tedious and might not accurately simulate the real service. 
Betamax aims to solve these problems by intercepting HTTP connections initiated by your application and replaying previously recorded responses.
The first time a test annotated with @Betamax is run any HTTP traffic is recorded to atape and subsequent test runs will play back the recorded HTTP response from the tape without actually connecting to the external server. 
Tapes are stored to disk as YAML files and can be modified (or even created) by hand and committed to your project’s source control repository so they can be shared by other members of your team and used by your CI server. Different tests can use different tapes to simulate various response conditions. Each tape can hold multiple request/response interactions. An example tape file can be found here.
Betamax works with JUnit and Spock. Betamax is written in Groovy, but can be used to test applications written in any JVM language.

For more information please visit:


No comments: