, , , ,

As some of you might know, QA’s usually don’t have to write Unit tests. But in some rare moments we get that task on our list of TODO’s. Recently, I had to write an unit test for a project. Unit tests aren’t that difficult in my point of view- if you know how to do one, you basically know how to do  them all. That is, if you don’t get something like this…

The problem here is, as you can see, that with the game “Snake” you are strictly console and time dependent. Some people might say “Pff, what’s the prob? Just redirect the console and presto!”. Well, that usually works, but here you have some functions that work only on Console, like Clear(), SetCursorPosition(), WindowWidth property. So, how do you test such a class then? Here comes my wacky “beginner type” solution 😀

Test Console Class

The code of the TestConsole class is publicly accessible here. It is created to be used as an object, for easier management. It works closely to our well known console, but this one has some unique methods:

  • SetKeys() – used to set the input keys, this method mimics a user pushing keys on the keyboard. It can be set with a manual timer, which can be ticked down by X seconds with the function KeyTickTimer(int ticks). When the counter hits 0, the key corresponding to it is accessible(i.e. it’s like the user has pressed it)
  • SetIn() – uses a string, to mimic a user input. Remember, each input in the console ends with “\n” or “\n\r”, so you can have multiple inputs in one string, but each must end with “\n” or “\n\r” (ex. “Alexander\n21\nGermany\nBerlin”)
  • GetOutput() – when you have finished, this method will return the output of the testConsole as a string. The output doesn’t include the “user’s” input.
  • KeyTickTimer() – as I explained previously, if you set your keys with corresponding timers for each of them, you can use this method to imitate a user’s delay before pressing a key. Using this method lowers the timer with an int value. When the timer reaches zero(“0”), the next key will be available. If you haven’t set timers for your keys, this method will do nothing