单元测试时,应该如何处理测试对象的初始化? [英] When unit testing, how should one handle testing the initialization of objects?

查看:46
本文介绍了单元测试时,应该如何处理测试对象的初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于我遇到的大多数单元测试实用程序,您通常可以访问某种 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?

推荐答案

对象的初始化是由构造函数完成的,所以测试初始化​​"就是测试构造函数".在测试普通的 mutator 方法时,您将执行感兴趣的方法,然后对对象的状态进行断言.对于构造函数来说是一样的.如果您在 setUp() 方法中创建测试夹具,与测试普通方法的唯一区别是测试方法本身不调用构造函数,而是依赖于设置方法中的调用.

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.

也就是说,我已经摆脱了让 ThingTest 类测试类 Thing 具有类 Thing 的测试装置的风格.我改为直接在测试方法中创建类 Thing 的对象,使用参数化测试来减少代码重复.我发现这避免了 神秘客人 代码气味.

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.

这篇关于单元测试时,应该如何处理测试对象的初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆