Unit testing helper or non-interface traits in Scala

只谈情不闲聊 提交于 2019-11-30 08:50:56

You can write an Helper mock trait which should be mixed with HttpHelpers and override its methods with mock equivalent:

trait HttpHelpersMock { this: HttpHelpers =>

  //MOCK IMPLEMENTATION
  override protected def withResponse[A](resp: HttpResponse)(fun: HttpResponse => A): A = // ...

  //MOCK IMPLEMENTATION
  override protected def makeGetRequest(url: String): HttpResponse = // ...
}

Then, when testing crawler, you mix the mock trait at instantiation:

val crawlerTestee = new Crawler(x) with HttpHelpersMock

And the mock methods will just replace the helper methods in instance crawlerTestee.

Edit: I don't think its a good idea to test how a class interacts with an helper trait. In my opinion, you should test Crawler behavior and not its internal implementation detail. Implementations can change but the behavior should stay as stable as possible. The process I described above allows you to override helper methods to make them deterministic and avoid real networking, thus helping and speeding tests.

However, I believe it make sense to test the Helper itself, since it may be reused elsewhere and has a proper behavior.

How about:

val helpers = new HttpHelpers {
  //override or define stuff the trait needs to work properly here
}

helpers.someMethodToTest

Look, Ma, no intermediate traits and mocking libraries needed!

I do that all the time for my traits and I've been pretty happy with the result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!