Using Cucumber for Unit Tests

Datetime:2016-08-23 01:14:04          Topic: Unit Testing           Share

Cucumber is usually considered a customer acceptance test automation tool. However, it can also be used as more of a unit testing tool in place of JUnit or other language-based tools. This can make those tests better and more understandable, with the probably of better maintainable code underneath.

The Example

One team I worked with had the job of converting a comma delimited file to a XML style file. They had coded the tests in JUnit. To show the alternative, we converted these to Cucumber tests. They had many other files for which they had to do a similar conversion. After seeing the possibilities, they switched to Cucumber.

Here’s a de-identified example acceptance test:

Given an input file in comma delimited format 
"""
123, John, 1 Apple Lane, 27701,
"""
When it processed and validated
Then the output is in XML format. 
"""
<Customer> 
  <Id>123</Id>
  <Name>John</Name>
  <Street>1 APPLE LANE</Street> 
  <ZipCode>27701-3204</Zipcode>
</Customer>
"""

This was the overall acceptance test. There are a few steps in the process to accomplish the conversion. They are:

  • Input the file into a domain object
  • Validate the domain object against an external service (USPS validator)
  • Output the domain object in XML format

The methods that performed each of these steps was tested with JUnit style tests. The alternative is to create Cucumber tests for them. They looked something like:

Scenario: Convert CSV file to Customer
Given
"""
123, John, 1 Apple Lane, 27701,
"""
When address is converted from CSV
Then Customer should be:
| Id    | Name    |   Street     | Zip Code | 
| 123   | John    | 1 Apple Lane | 27701    | 
# 
@RequiresExternalService
Scenario:  Validate address
Given Customer is:
| Id    | Name    |   Street     | Zip Code | 
| 123   | John    | 1 Apple Lane | 27701    | 
When Address Validator executes
Then Customer should be:
| Id    | Name    |   Street     | Zip Code      | 
| 123   | John    | 1 APPLE LANE | 27701-3204    | 
#
Scenario: Convert Customer to XML 
Given Customer is:
| Id    | Name    |   Street     | Zip Code      | 
| 123   | John    | 1 APPLE LANE | 27701-3204    |
When Customer is converted to XML
Then Customer XML should be:
"""
<Customer> 
  <Id>123</Id>
  <Name>John</Name>
  <Street>1 APPLE LANE</Street> 
  <ZipCode>27701-3204</Zipcode>
</Customer>
"""




About List