DAMP not DRY

Often people will talk about Don’t Repeat Yourself as a way of minimising the amount of duplication/repetition of tasks. In general it is a great thing to keep in mind. However, when it comes to writing tests, often it is preferable to favour expressiveness at the ’expense’ of repetition. This is referred to as Descriptive And Meaningful Phrases.

Example

The two example unit tests below share duplicated code in their setup sections (you could move the standardProduct setup code into a helper method), but duplicating the code makes each test readable in its own right:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

def "pickFabricUrl is constructed as expected with legType"() {
  given:
  def standardProduct = Mock(StandardProduct)
  standardProduct.getName() >> "product-name"
  standardProduct.getId() >> "product-id"
  def legType = "legType"

  def asafProductPickFabricUrl = new AsafProductPickFabricUrl(standardProduct, legType)

  when:
  def pickFabricUrl = asafProductPickFabricUrl.toString()

  then:
  pickFabricUrl == "/product-name/pproduct-id/fabrics?legType=$legType"
}

def "pickFabricUrl is constructed as expected without legType"() {
  given:
  def standardProduct = Mock(StandardProduct)
  standardProduct.getName() >> "product-name"
  standardProduct.getId() >> "product-id"

  def asafProductPickFabricUrl = new AsafProductPickFabricUrl(standardProduct, null)

  when:
  def pickFabricUrl = asafProductPickFabricUrl.toString()

  then:
  pickFabricUrl == "/product-name/pproduct-id/fabrics"
}