scala – 在Spec2中的每个测试之前执行reset方法

我在测试类中使用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

在这些方法中,我正在检查是否调用了定义的mock.但是我需要重新创建一个模拟,所以我只能为一个非全局的方法计算调用.

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

 def prepareMocks = {
   serviceMock = mock[MyService]
 }

这将在每个测试方法之前执行,所以我在检查我的断言之前已经准备好了clean mock.

我尝试使用Spec2中的特征BeforeEach和BeforeExample,但它们不是我想要的.

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

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
  }
}
点赞