lundi 20 mai 2019

Scala, Specs2 and shared state

I am writing some Specs2 specifications; that looks like:

class ComponentSpecification extends Specification with Mockito {

  private val dependency = mock[Dependency]
  private val subject = new Component(..)

  "methodOne" should {
    "handle happy path" in {
       val result = subject.methodOne("Param1", 42)
       result must ...
       there was one(dependency).something()
    }

    "deal with border case" in {
       val result = subject.methodOne("", -1)
       result must ...
       there was one(dependency).something()
    }
  }
}

However, those tests fails because the mock[Dependency] is shared.

  • One solution would be to make them sequential and reset the mock before each test but this look odd and as written in the doc about "Parallel by default":

it encourages to write independent examples when the result of a given example should not be influenced by others

  • Another would be to move the val to the test itself. But while I should be able to reduce the duplication with this still looks like a strange structure. And looks like the subject is stateful while it should not.

  • I can also try to use a less strict approach by verifying with there was atLestOne(dependency).something() but:

    1. this does not validate that the method was called in this specific test case and
    2. argument capture and validation is painful.

So my question is:

How can I create readable tests with detailed verifications on mock.

Thanks a lot.

Aucun commentaire:

Enregistrer un commentaire