如何对顺序逻辑进行单元测试? [英] How to unit-test sequential logic?

查看:93
本文介绍了如何对顺序逻辑进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的Car类具有以下方法:

Suppose I have class Car with following methods:

  • 负载汽油(燃油)
  • InsertKey(IKey密钥)
  • StartEngine()
  • IDrivingSession Go()

Car的目的是配置并返回IDrivingSession,其余的应用程序将使用该IDrivingSession来驾驶汽车.如何对汽车进行单元测试?

the purpose of Car is to configure and return an IDrivingSession which the rest of the application uses to drive the car. How do I unit-test my Car?

在我可以调用Go()方法之前,它似乎需要完成一系列操作.但是我想分别测试每种方法,因为它们都有一些重要的逻辑.我不想像一堆单元测试

It looks like it requires a sequence of operations done before I can call Go() method. But I want to test each method separately as they all have some important logic. I don't want to have bunch of unit-tests like

Test1: LoadGasoline, Assert

Test2: LoadGasoline, InsertKey, Assert

Test3: LoadGasoline, InsertKey, StartEngine, Assert

Test4: LoadGasoline, InsertKey, StartEngine, Go, Assert

没有更好的方法来对顺序逻辑进行单元测试,还是我的Car设计存在问题?

Isn't there a better way to unit-test sequential logic or is this a problem with my Car design?

-编辑- 感谢所有的答案.正如许多人所注意到的,我也应该对无效的场景进行测试,我也应该对它们进行测试,但是这个问题集中在如何测试有效的序列上.

--- EDIT ---- Thanks for all the answers. As many noticed, I should also have tests for invalid scenarios and I have those too, but this question is focused on how to test the valid sequence.

推荐答案

我认为每种方法都应分别进行独立测试.

I think each method should be tested separately and independently.

恕我直言,您应该为每种情况准备环境,因此,如果更改LoadGasoline方法,则只有LoadGasoline测试会中断,并且您将不需要查看所有测试是否由于单个错误而中断.

IMHO, you should prepare the environment for each case, so only the LoadGasoline test will break if you change the LoadGasoline method, and you won't need to see all the tests break because of a single bug.

我不知道您的Car的状态如何,但是在InsertKey之前,您应该使用car.SetTotalGasoline(20)之类的方法进行准备.或此方法中设置的任何变量,但不依赖于方法LoadGasoline的复杂逻辑.

I don't know how the state of your Car looks like, but, before the InsertKey, you should prepare with a method like, car.SetTotalGasoline(20); or whatever variable is set in this method, but not depend on a complex logic of the method LoadGasoline.

您稍后将需要测试(在这种情况下,不是单元测试)来测试所有序列.

You will later need a test (in this case, not a unit test) to test all the sequence.

这篇关于如何对顺序逻辑进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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