这是我的测试:
object MySpek : Spek({
val myMock1: MyMock1 = mock()
val myMock2: MyMock2 = mock()
val handler = StartModeHandler(myMock1, myMock2)
val session = mock<Session> {
on { user }.doReturn(User.builder().withUserId("userId").build())
}
describe("item exists for user") {
beforeGroup {
reset(digitalPointDao, trackDao)
}
whenever(myMock1.loadItem(session.user.userId)).thenReturn(Optional.of(MyItem()))
whenever(myMock2.loadSomething()).thenReturn(ArrayList())
context("method onLaunch was called") {
val response = handler.onLaunch(session)
it("should return the response for existing user") {
//some asserts here
}
it("should save the item") {
//some mock verifies here
}
}
}
})
根据Spek的文档,我希望流程如下:
但我得到以下流程:
我错过了什么,在这里做错了吗?
答案 0 :(得分:0)
正如Spek文档组中所提到的,范围(给定,描述,上下文)将热切地执行其中的任何代码。任何测试状态初始化都应该在fixtures中完成(beforeEachTest,beforeGroup等...)。您还可以使用memoized
创建与Spek生命周期相关的依赖关系。
object MySpek: Spek({
val myMock1 by memoized { mock<myMock1>() }
val myMock2 by memoized { mock<myMock2>() }
val handler by memoized { StartModeHandler(myMock1, myMock2) }
val session by memoized {
mock<Session> {
on { user }.doReturn(User.builder().withUserId("userId").build())
}
}
describe("item exists for user") {
beforeEachTest {
reset(digitalPointDao, trackDao)
whenever(myMock1.loadItem(session.user.userId)).thenReturn(Optional.of(MyItem()))
whenever(myMock2.loadSomething()).thenReturn(ArrayList())
}
// use on instead of context
on("method onLaunch was called") {
val response = handler.onLaunch(session)
it("should return the response for existing user") {
//some asserts here
}
it("should save the item") {
//some mock verifies here
}
}
}
})