Specs2 - 方法内的模拟对象

时间:2015-12-09 13:33:08

标签: scala mocking playframework-2.0 specs2

我正在编写单元测试,我想知道是否可以模拟在我测试的方法中实例化的对象。

以下是我想测试的方法示例:

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
} 

我想知道是否可以做类似的事情:

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

有可能吗?

我尝试过使用spy()和mock,但没有成功:

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())

关于我该怎么做的任何想法?

1 个答案:

答案 0 :(得分:0)

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! 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). You will be interested in following this SOF question then.