What are some strategies for testing large state machines?

后端 未结 9 1675
刺人心
刺人心 2021-02-01 05:51

I inherited a large and fairly complex state machine. It has 31 possible states, all are really needed (big business process). It has the following inputs:

  • Enum: C
9条回答
  •  鱼传尺愫
    2021-02-01 06:24

    I see the problem, but I'd definitely try splitting the logic out.

    The big problem area in my eyes is:

    • It has 31 possible states to be in.
    • It has the following inputs:
      • Enum: Current State (so 0 -> 30)
      • Enum: source (currently only 2 entries)
      • Boolean: Request
      • Boolean: type
      • Enum: Status (3 states)
      • Enum: Handling (3 states)
      • Boolean: Completed

    There is just far too much going on. The input is making the code hard to test. You've said it would be painful to split this up into more manageable areas, but it's equally if not more painful to test this much logic in on go. In your case, each unit test covers far too much ground.

    This question I asked about testing large methods is similar in nature, I found my units were simply too big. You'll still end up with many tests, but they'll be smaller and more manageable, covering less ground. This can only be a good thing though.

    Testing Legacy Code

    Check out Pex. You claim you inherited this code, so this is not actually Test-Driven-Development. You simply want unit tests to cover each aspect. This is a good thing, as any further work will be validated. I've personally not used Pex properly yet, however I was wowed by the video I saw. Essentially it will generate unit tests based on the input, which in this case would be the finite state machine itself. It will generate test cases you will not have enough thought of. Granted this is not TDD, but in this scenario, testing legacy code, it should be ideal.

    Once you have your test coverage, you can begin refactoring, or adding new features with the safety of good test coverage to ensure you don't break any existing functionality.

提交回复
热议问题