Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test sequential logic?

Suppose I have class Car with following methods:

  • LoadGasoline(IFuel gas)
  • InsertKey(IKey key)
  • StartEngine()
  • IDrivingSession Go()

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?

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

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.

like image 263
Stop Putin Stop War Avatar asked Feb 28 '23 15:02

Stop Putin Stop War


1 Answers

I think each method should be tested separately and independently.

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.

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.

like image 112
Samuel Carrijo Avatar answered Mar 13 '23 04:03

Samuel Carrijo