简体   繁体   English

Specs2-模拟方法内部的对象

[英]Specs2 - Mock objects inside method

I'm writting unit tests and i would like to know if it's possible to mock an object that is instanced inside the method that i'm testing. 我正在编写单元测试,我想知道是否有可能模拟我正在测试的方法内部实例化的对象。

Here is an example of a method that i would like to test: 这是我要测试的方法的示例:

def sendMessageToBroker(message:Message) = {

  val soapBody = xmlBody("user", "pass", message.identifier, 
      message.to, message.message)

  val response = new WebServiceUtil().doPost("uri", soapBody.toString(),
  "text/xml; charset=utf-8", "action")

  response
} 

I was wondering if it's possible to do something like: 我想知道是否可以做类似的事情:

when call doPost, return new Response(200, 'Success')

Is it possible? 可能吗?

I've tried do it using spy() and mock, but no sucess: 我试过使用spy()和模拟,但没有成功:

val ws = new WebServiceUtil

val spiedObj = spy(ws)
spiedObj.doPost("uri", xml,
  "text/xml; charset=utf-8",
  "action") returns new Response(200, "Success")

val xx = messageService.sendMessageToBroker(new Message())

Any ideas on how can i do it? 关于我该怎么办的任何想法?

You could write 你可以写

val webService = mock[WebServiceUtil]

webService.doPost("uri", xml, "text/xml; charset=utf-8", "action") returns 
   new Response(200, "Success")

// pass the mock webservice as an argument
sendMessageToBroker(new Message, webService)

The important part is that you need to be able to pass a mock WebServiceUtil to your method being tested! 重要的是,您需要能够将模拟WebServiceUtil传递给要测试的方法! There are many ways to do that. 有很多方法可以做到这一点。 The simplest one is to pass the instance to a constructor method of our "class under test": 最简单的方法是将实例传递给我们“被测类”的构造方法:

class MyClass(webService: WebServiceUtil) {
  def sendMessageToBroker(message: Message) = {
    // use the webservice
  }
}

A more involved method would use Guice and the Inject annotation to pass the service (especially since you tagged the question as a play-framework-2.0 one). 一种更复杂的方法是使用Guice和Inject批注来传递服务(特别是因为您将问题标记为play-framework-2.0 )。 You will be interested in following this SOF question then. 然后,您将有兴趣关注此SOF问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM