Kotlin Spek中的组执行顺序错误

时间:2017-09-09 12:40:02

标签: java unit-testing testing kotlin spek

这是我的测试:

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的文档,我希望流程如下:

  1. 在描述之前初始化所有内容
  2. 调用beforeGroup
  3. initalize描述身体,例如我每当要求嘲笑
  4. run context
  5. 运行每个方法
  6. 但我得到以下流程:

    1. 在描述之前初始化所有内容
    2. 运行我描述的身体,例如我每当要求嘲笑
    3. run context
    4. run beforeGroup
    5. 运行每个方法
    6. 我错过了什么,在这里做错了吗?

1 个答案:

答案 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
            }
        }

    }
})