4

我在使用 Spec2 的测试类中有一个定义的测试方法链:

def is =
  "EntriesServlet with logged user" ^
  "POST / request should update entry that user owns" ! updateExistingEntryThatLoggedUserOwns ^
  "POST / request should not update non existing entry" ! notUpdateNonExistingEntry ^
  "POST / request should not update non owner entry" ! notAllowToUpdateNotOwnedEntry
end

在这些方法中,我正在检查是否调用了定义的模拟。但是我需要重新创建一个模拟,这样我就可以只计算一种方法的调用,而不是全局的。

所以我需要一种无缝定义方法的方法让我们说:

 def prepareMocks = {
   serviceMock = mock[MyService]
 }

这将在每个测试方法之前执行,所以在检查我的断言之前我已经准备好了干净的模拟。

我尝试了特征BeforeEachBeforeExampleSpec2,但它们不是我想要的。

4

1 回答 1

2

您可以使用案例类来实例化您的模拟并将它们与同时执行的其他示例隔离开来:

import org.specs2._
import specification._
import mock._

class MySpec extends Specification { def is =
  "EntriesServlet with logged user" ^
    "POST / request should update entry that user owns" !        c().updateExistingEntryThatLoggedUserOwns ^
    "POST / request should not update non existing entry" ! c().notUpdateNonExistingEntry ^
    "POST / request should not update non owner entry" ! c().notAllowToUpdateNotOwnedEntry ^
  end

  trait MyService
  case class c() extends Mockito {
    val service = mock[MyService]

    def updateExistingEntryThatLoggedUserOwns = service must not beNull
    def notUpdateNonExistingEntry = ok
    def notAllowToUpdateNotOwnedEntry = ok
  }
}

// here's a similar solution using standardised group names which is a 1.12.3 feature

class MySpec extends Specification { def is =
  "EntriesServlet with logged user" ^
    "POST / request should update entry that user owns"   ! g1().e1 ^
    "POST / request should not update non existing entry" ! g1().e2 ^
    "POST / request should not update non owner entry"    ! g1().e3 ^
  end

  trait MyService
  "POST requests" - new g1 with Mockito {
    val service = mock[MyService]

    e1 := { service must not beNull }
    e2 := ok
    e3 := ok
  }
}
于 2012-11-26T09:51:18.487 回答