JUnit 最佳实践:每个 @Test 都有不同的装置
据我所知,有 @Before
和 @BeforeClass
,它们用于定义 @Test
的固定装置。但是,如果每个 @Test
需要不同的装置,我应该使用什么?
- 我应该在中定义夹具吗
@Test
? - 我应该创建一个测试类吗 对于每个
@Test
?
我在这里寻求最佳实践,因为我认为这两种解决方案都不干净。对于第一个解决方案,我将测试初始化代码。通过第二个解决方案,我将打破“每个类一个测试类”的模式。
I understand that there are @Before
and @BeforeClass
, which are used to define fixtures for the @Test
's. But what should I use if I need different fixtures for each @Test
?
- Should I define the fixture in the
@Test
? - Should I create a test class
for each@Test
?
I am asking for the best practices here, since both solutions aren't clean in my opinion. With the first solution, I would test the initialization code. And with the second solution I would break the "one test class for each class" pattern.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
提示:
Tips:
我建议根据您需要的不同灯具创建一个单独的类。如果您有两个不同的灯具,则只需创建两个不同的类(给它们一个方便的名称)。但我会再考虑一下这个问题,特别是赛程的差异以及为什么不同。也许您正在进行某种集成测试而不是单元测试?
I would suggest to create a separate Class based on the different fixtures you need. If you have two different fixtures you need just create two different classes (give them a convenient name). But i would think a second time about that, in particular about the difference in the fixtures and why are the different. May be you are on the way to a kind of integration test instead of unit test?
如果您确信您的装置对于单个测试是唯一的,那么它属于
@Test
方法。但这并不典型。它的某些部分可能是唯一的,或者您没有正确参数化/提取它,但通常您会在测试之间共享许多相同的数据。最终夹具是测试的一部分。将固定装置放在
@Before
中被采用作为 xUnit 模式,因为测试总是:和步骤 1 (
@Before
)和4(@After
)在相关测试中被大量(至少部分)重用。由于 xUnit 非常重视测试独立性,因此它提供了固定方法来保证它们始终正确运行和测试创建/销毁的数据。If you are positive that your fixture is unique to single test then it belongs to
@Test
method. This is not typical though. It could be that some part of it is unique or you didn't parametrize/extracted it right, but typically you will share a lot of the same data between tests.Ultimately fixture is part of the test. Placing fixture in
@Before
was adopted as xUnit pattern because tests always:and steps 1 (
@Before
) and 4 (@After
) are reused a lot (at least partially) in related tests. Since xUnit is very serious about test independence it offers fixture methods to guarantee that they always run and test data created/destroyed properly.