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

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

问题描述

因此,在我遇到的大多数单元测试实用程序中,通常都可以访问某种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()方法中创建测试装置,则与测试常规方法的唯一区别在于,测试方法不会自行调用构造函数,而是依赖于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.

也就是说,我已经离开了测试类ThingThingTest类具有类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天全站免登陆