在测试类中重用业务逻辑以节省时间 [英] reusing business logic in a test class to save time

查看:19
本文介绍了在测试类中重用业务逻辑以节省时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是和办公室里的人聊了聊使用业务逻辑类来构建一些数据以测试另一个类.

Just having a conversation with someone in the office about using a business logic class to build up some data in order to test another class.

基本上,他有一个类 A,它将一个复杂类型作为参数,然后生成一个不同复杂类型的集合.他已经在这门课上写了测试.现在他开始测试另一个类(B 类),该类获取 A 类的结果,然后对其执行一些逻辑.

Basically, he has class A which takes a complex type as a parameter and then generates a collection of a different complex type as a result. He's written tests around this class already. Now he's moved on to testing another class (class B) which takes the result of class A then performs some logic on it.

他问了一个问题,我应该使用 A 类来构建一个场景来测试 B 类吗".

He's asked the question, "should I use class A to build up a scenario to test class B with".

起初我说是,因为 A 班有测试.但后来我很清楚,如果 A 类中存在一些我们尚未发现的错误会怎样……所以我想一定有更好的方法来解决这种情况.

At first I said yes as class A has tests around it. But then I figured well what if there's some bugs in class A that we haven't found yet... so I guess there must be a better way to address this scenario.

有人对此有什么想法吗?是否可以使用现有逻辑来节省编写其他测试的时间?

问候,

詹姆斯

推荐答案

对此的立场可能有所不同.通常,如果代码经过测试并且您假设它可以工作,您就可以自由使用它.当使用已经测试过的方法来帮助测试其他人(在单个类/单元中)时尤其如此.但是,由于这是在单个单元内发生的,因此与您的情况略有不同.

Stances on that might differ. Generally, if code is tested and you assume it works, you're free to use it. This is especially true when using already tested methods to help with testing others (within single class/unit). However, as this happens within single unit it's a bit different from your case.

现在,在处理 2 个单独的类时,我会说您应该避免这种方法.纯粹是因为这两个类可能没有明显的关联,或者它们的上下文/使用范围可能大不相同.例如,有人可能在不知道 B 类存在的情况下更改 A 类.即使未对 B 代码进行任何更改,B 类测试也会突然中断.这会带来不必要的混乱,而且是您通常不想遇到的情况.

Now, when dealing with 2 separate classes I'd say you should avoid such approach. Purely for the reason that those two classes might not be related in obvious way or their context/scope of usage might vastly differ. As in, somebody might change class A without even knowing class B exists. Class B tests suddenly break even though no changes were made to B code. This brings unnecessary confusion and is situation you usually don't want to find yourself in.

相反,我建议在经过测试的 B 类文件中创建辅助方法.使用存根/伪造品和诸如 AutoFixture 之类的工具,您应该能够轻松地重现 A 类使用的生成逻辑和在 B 类测试中包含您自己的副本".

Instead, I suggest creating helper method within tested class B file. With stubs/fakes and tools like AutoFixture, you should be able to easily reproduce generation logic used by class A and have your own "copy" contained in class B tests.

这篇关于在测试类中重用业务逻辑以节省时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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