How to reuse code in repetitive Unit Tests #174
-
So I have an application where a variety of status words can lead to the same state in my code. I want to test all of the status/state combinations and started out by making one test per state where within the test I kept changing the status word and redoing my assertions. After a closer look at the FB_Sum_Test example, I thought, "better to make my code very modular, let me make one test per status/state combination". That worked alright, but I was cutting and pasting lots of code... which seemed bad. I then tried sending the status to the argument of my test... ie:
which makes for cleaner (and fewer) methods within my test function block, BUT... I can't run the same Test multiple times in one test suite. In attempting to, I get the totally reasonable error:
I've seen other posts on this forum about people bundling tests and I'm wondering how others deal with this type of situation. Or is this just a case where it's necessary to have something like VFD_OFF1_Stopping_Test, VFD_OFF2_Stopping_Test etc even though all the tests are basically the same? If I need all these individual tests, would it work to outsource the assertion parts of the test to a function that I reuse or must the AssertEquals() be in the test itself? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
I'm going to reply to myself here and say that I ended up deciding to loop through all the possible status-words in each test. This way I had fewer additional functions and no repeat calls to tests. This seems like a cleaner way to approach it than what I had; I'd still be curious to know what other people do in this situation. |
Beta Was this translation helpful? Give feedback.
-
You can declare a testmethod named:
And the code (example)
The Call
Be sure to call the testSuite
I use this way of repeated testing all the time and works like a charm. With kind regards, Aliazzz |
Beta Was this translation helpful? Give feedback.
-
"That way, code reuse is minimized." => you probably mean reuse is maximized as code duplication is minimized ;-) So your approach is to have helper methods to skip or manipulate the state machine into the desired testing state and then do the required test. Yes, this seems a valid approach which also allows for randomization and thus should prove that there are no interdependences between testee or separate tests. The randomization is as said before, just an extra cherry which you could do without. Primer In short: Sometimes the anwser can be so easy! |
Beta Was this translation helpful? Give feedback.
You can declare a testmethod named:
And the code (example)