mercredi 21 octobre 2020

Do you write helper methods when invoking production code in tests to hide some irrelevant details?

Let's say that I have an example test case (written in Kotlin, but it doesn't matter here)

@Test
fun `should do something`() {
    // given
    val expected = "expected result"

    // when
    val result = productionClass.process("foo", null)

    //then
    assertThat(result).isEqualTo(expected)
}

As you can see I'm passing a null value as a second parameter to process method because it's not relevant in this case so I can ommit this.

But my concern is that every time I'm reading this test I'm wondering why this null value is passed and what does it mean in this context, so my solution to this problem is to create some helper method which hides this null for me. Then my test would looke like this

@Test
fun `should do something`() {
    // given
    val expected = "expected result"

    // when
    val result = process("foo")

    //then
    assertThat(result).isEqualTo(expected)
}

private fun process(foo: String): String {
    return productionClass.process(foo, null)
}

Then when I'm reading the test it's clear for me what is happening, but as always there are pros & cons of such solutions. These are the ones that I found:

Pros

  • improved readability of the test
  • small decoupling of production code from tests (change of the production API causes only this helper to break, not 100 other tests)
  • hiding low level details from test, I'm only intrested in the result, it's not important here how it happens (maybe... or maybe I'm wrong here)

Cons

  • I'm not really sure what the test does as it can do many weird things in this helper
  • Creating one helper can lead to creation of many other helpers, and then I won't be able to find what is going on

I'm really curious about your opinion. How do you handle this problem? Or maybe it's not a problem at all?

Aucun commentaire:

Enregistrer un commentaire