在单元测试时,应该如何处理对象初始化的测试?

发布于 2024-12-12 18:59:16 字数 293 浏览 1 评论 0原文

因此,对于我遇到的大多数单元测试实用程序,您通常可以访问某种 SetUp() 和 TearDown() 函数。虽然我发现这对于几乎每个单元测试都非常方便,但我想知道应该如何处理对象初始化的测试?我的意思是,在几乎所有其他测试中,您只需让 SetUp() 函数处理它即可。然而,在我使用过的大多数基本测试实用程序中,SetUp() 在每个测试之前被调用。我一直想知道您是否只在 SetUp() 函数中进行初始化测试,是否应该创建自己的 SetUp() 等效函数,该函数在与初始化测试无关的测试开始时显式调用,或者是否有其他一些普遍接受的做法我没有提出来吗?

So with most unit testing utilities I have come across, you usually get access to a SetUp() and TearDown() function of some sort. While I see that this comes in very handy for almost every unit test, I was wondering how testing the initialization of objects should be handled? I mean, in almost every other test, you would just let the SetUp() function handle it. However, in most of the basic testing utilities I have worked with, SetUp() gets called before every test. I have been wondering if you just do the initialization testing within the SetUp() function, if one should make their own SetUp() equivalent function that gets called explicitly at the beginning of tests not related to initialization testing, or if there is some other generally accepted practice I have not brought up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静谧 2024-12-19 18:59:16

对象的初始化是由构造函数完成的,因此“测试初始化​​”意味着“测试构造函数”。当测试普通的修改器方法时,您将执行感兴趣的方法,然后对对象的状态进行断言。对于构造函数来说是一样的。如果您在 setUp() 方法中创建测试装置,则与测试普通方法的唯一区别是测试方法不会调用构造函数本身,而是依赖于 setup 方法中的调用。

也就是说,我已经放弃了使用 ThingTest 类测试类 Thing 具有类 Thing 的测试装置的风格。相反,我直接在测试方法中创建类 Thing 的对象,使用参数化测试来减少代码重复。我发现这避免了神秘来宾代码味道。

The initialization of an object is done by a constructor, so "testing initialization" means "testing the constructors". When testing a normal mutator method you would execute the method of interest, then make assertions about the state of the object afterwards. For a constructor it is just the same. The only difference from testing a normal method, if you create test fixtures in your setUp() method, is that the test methods do not call the constructor themselves, but rely on the call in the set up method.

That said, I've moved away from the style of having the ThingTest class that tests class Thing have test fixtures of class Thing. I instead create the objects of class Thing directly in the test methods, using parameterised tests to reduce code duplication. I find this avoids the mystery guest code smell.

梦罢 2024-12-19 18:59:16

你可能想太多了。实现 setUp() 是可选的,任何给定的测试都可以忽略 setUp() 创建的任何状态。因此,您可以简单地忽略测试对象初始化的一个测试方法的状态,或者创建一个单独的测试类,仅用于测试具有空 setUp() 方法的初始化。

You may be overthinking this. Implementing setUp() is optional, and any given test is free to ignore any state created by setUp(). So you can either simply ignore that state for one test method that tests object initialization, or create a separate test class just for testing initialization which has an empty setUp() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文