问题
I have seen Spock tests where mocks are wired up & configured in the given
block (which is where it makes the most sense to me), as well as cases where the only way to get the test to pass required me to wire/configure the mocks inside the then
block, which is just plain silly to me. An example of the latter is a question that I asked some time ago.
So I ask: What determines where to actually wire/config a mock, either in given
or in then
? I really hope the answer isn't just "keep playing with it until it works", because that's too non-deterministic for my tiny robot brain.
回答1:
Mocks and Stubs should be instantiated in the setup
/given
block or even in setup()
method if you are going to use them in multiple tests and want to reduce boilerplate.
In my opinion, Mocks and Stubs behavior should be defined in the most-narrowly scoped place that makes sense. then
makes the most sense usually, but defining general behavior that you don't really care about checking closely could be put in the setup
/given
block or even in the setup()
method.
来源:https://stackoverflow.com/questions/37072767/spock-block-mocks-and-where-to-wire-them