Thursday 15 July 2010

unit testing - How can I inject a dependency on a singleton object? -


Let's say I'm testing a method on which there is dependency on a single (imported) Singleton instance called WS (web service), which has it. One method, url (url: string) , which returns a URL and returns a request.
  def doRequest (url: string): future [feedback] = {val request = for WS.url (url) {feedback < - request.post (params)} yield {val res: JsResult [MyResult] = response.json.validate [MyResult] res.getOrElse (New NotSupportedException Throw)}}   

I WS Dependency I would like to be able to inject as my unit tests do not require a real outbound http request, but instead can depend on a fake WS example

This has been a challenge for me because A singleton technically does one type (class [WST] Ip]), the properties and methods of WS are lost when Singleton requires a Val that expects class [WS.type], that means that I can not just use a simple cake pattern like: < /p>

  Properties WSComponent {val: ws: class [_ & lt;: WS.type}} Object ApplicationContext WSComponent {val ws = WS} Object Test Context WSComponent {val ws = mock [ws]}   

, and then in the context of WS methods in any context, I get a compilation error, which means that [_ & Lt;: WS.type] in no way (for example) url ().

Looks like a similar reason (basically, there are no types in single objects - even though they do--), I can not provide an indirect parameter that is a W. Because S. again, because again, I will lose the declared methods and properties on single methods.

What are the perspectives for single-object dependency injection? I like to enjoy cake pattern for DI, but it offers a lot of boilerplate for my code, so the ideal solution will not combine the code with more boilerplate.

Thanks in advance for any suggestions.

There are types of singleton objects, and you can call methods on them:

  Scala> Val I: Int.type = Int i: Int.type = Object scale. Intake Scale & gt; I.box (42) res0: integer = 42   

I think what to do with your error

  val ws: class [_ &  

> It can not be compiled, and in fact there is a class [...] any url () method is not just you ws From WS.type to: WSComponent {val ws: WS.type}

  Pre> 

and Fake [WS.type] Change the joke to


Edit : The other route below works only when you have control over the WS type (apparently this It is not the case because it comes from the game)

If you really want to avoid the singleton type, you can use the WS

  attribute WS {DRAR URL (url: string): request} extends object singletonwaves to ws {/ code> one with singleton implementation Refer to the specialty in the specialty, and only in your cake. Def url (url: string) = ??? // real implementation}   

and in your cake:

  Properties WSComponent {val ws: WS} object applicationContact WSComponent {val ws = SingletonWS} object Enhances TestContact extends to WSComponent {val ws = mock [ws]}    

No comments:

Post a Comment