在哪里放置几个 Grails 测试类中使用的可重用测试方法
我经常需要为不同的测试用例设置相同的测试结构。因此,我创建了一个 TestService 类,它具有多个测试类的公共方法。
我想这不是放置它们的最佳位置,因为 TestService 也将被部署,尽管在生产中不需要。
你会把那些常用的测试方法放在哪里?这有“最佳实践”吗?
I often need to set up the same test structures for different test cases. Therefore I created a TestService class that has several public methods for the test classes.
I guess that this is not the best place to put them as TestService will also be deployed although not needed on production.
Where would you put those commonly test methods? Is there a "best practice" for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的做法和上面的答案类似。如果我有一个 MyDomain 类,我会将 MyDomainTestHelper 类放入测试包中。该帮助器具有返回相关域对象的静态方法。所以我可能有一个
创建一个具有合理默认值的实例,
这样我就可以指定一些东西等等。
正如您提到的,您不应该将它们放入“服务”中。但任何能让你保持 DRY 的方式都是好方法。
The way i do it is similar to the above answers. If I have a MyDomain class, I put a MyDomainTestHelper class in a test package. The helper has static methods on it that return the domain objects in question. So i might have a
that creates an instance with sensible defaults and
so I can specify something and so on.
You should not put them in a "service" as you mentioned. But any way you can be DRY is a good way.
在编写测试时,我倾向于尽量遵循 DRY 原则。这主要通过两种方式表现出来:
我通常实现一个
TestData
类,该类以静态属性保存我输入到测试中的所有数据,以便更轻松地跟踪我提供的输入测试,并确保当我打算提供相同的输入时,我不会给出不同的输入。它驻留在测试项目中,或仅由测试项目引用的类库中。如果我发现在许多测试中需要相同的设置或拆卸例程,我经常使用继承 - 创建一个测试装置可以继承的基类,所有常见操作都在其中。
脚注:我几乎所有的开发都是用 C# 进行的,但我相信这些实践可以应用于任何具有测试框架的语言。
I tend to try to keep to the DRY principle as much as I can when writing tests. This shows in mainly two ways:
I usually implement a
TestData
class, that holds all the data I feed into my tests in static properties, to make it easier to keep track of what input I give the tests, and to make sure I never give different input when I intend to give the same. This resides in a test project, or in a class library referenced only by the test projects.If I find I need the same setup or teardown routines in many tests, I often make use of inheritance - create a base class that the test fixtures can inherit, where all the common actions go.
Footnote: I do almost all of my development in C#, but I believe these practices can be applied in any language with a testing framework.
你为什么不把它放在你的测试课程旁边呢?通常的方法是将所有与测试相关的代码放入与源目录分开的目录中(例如“test”)。即不仅是测试用例本身,还包括支持类,例如实用方法、模拟实现等。
测试用例应该放入与它们测试的类相同的包中(但位于不同的物理目录中,如上所述) 。一个由多个测试用例使用的测试实用程序类应该放入某个公共实用程序包中。
Why don't you put it next to your test classes? The usual way is to put all test-related code into a directory separate from the source directory (e.g. "test"). I.e. not only the test cases themselves, but also supporting classes, such as utility methods, mock implementations etc.
The test cases should be put into the same package as the class tested by them (but in a different physical directory, as explained above). A test utility class which is used by several test cases should be put into some common utility package.