开发者

Unit testing console inputs and random numbers

I have a logic module for a turn based game (no UI yet), which uses async user input (parsed fr开发者_StackOverflowom console, until the real UI gets done), and in some cases generates random numbers ("die rolls") and makes changes in the game state-model based on the inputs and the random numbers.

Reading this thread and this thread, I was wondering if it was possible to use something similiar. My game logic has a single Random instance, so it should be relatively easy to swap that out.

So what do I have to do?

  • Swap out GameLogic.Random to an IRandom, and put either a Random or a pregenerated sequence into it based on whether I'm testing
  • Swap out Console.ReadLine() with IConsole.ReadLine() everywhere in my command parser so I don't have to type it in every time
  • Swap out Console.WriteLine() with IConsole.WriteLine() so it prints to a file, where I can read the results

And then I can use my classes from a Unit Test? That's all??


Yes, that's all, but you don't even have to do that, if you don't want to.

You don't have to create the interface IConsole, because in a way, it already exists. You can use TextReader for your input and TextWriter for your output. In real app, you pass in Console.In and Console.Out. In testing you can use StringReader and StringWriter.

You also don't have to create IRandom if you don't want to supply the numbers yourself and Random initialized to a constant seed is enough for you.


In a word: yes. Except it might be better to have your mock implementation of IConsole.WriteLine() just save the values it is given into a collection of strings you can read back from the mock instead of having to go to the trouble of writing to a file on disk then locating and reading that file back.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜