Q：How can I reuse some parts of my tests?

Q：我如何重用我的测试的某些部分？

I need to implement following logic:

Do something

Check logic

Do something other

Similar check logic

I used when/then blocks for simple tests. But I really don't know how to implement more complicated one (like described above) + I would like to reuse code as much as possible. But with blocks it becomes more complicated to implement

我需要实现以下逻辑：

Do something

Check logic

Do something other

Similar check logic

我用/然后块进行简单的测试。但我真的不知道如何实现更复杂的一个（如上所述）+我想重用代码尽可能。但随着块的实施变得更加复杂

answer1：

回答1：

There are a few approaches I take to reusing code in Spock.

Feature Level
Create a closure within your setup: block. You can treat it like a method that's available to only this feature.

Package Level
I have a group of classes that could all benefit from sharing a miniature testing framework. My preference is to use traits. They can hold any code except for a Feature test itself. If the trait will reference data from within the test itself, make sure to create an abstract method so the trait is ensured a reference to the data.

Package Level
I have a group of classes that could all benefit from sharing a miniature testing framework. My preference is to use traits. They can hold any code except for a Feature test itself. If the trait will reference data from within the test itself, make sure to create an abstract method so the trait is ensured a reference to the data.

However, if you find that your doStuff() is large and that many of your tests are using the same interaction method then it might be time to think about moving some code in your production class into a separate class and then having one expectation that your class under test calls your new class.