如何在测试方法中模拟按键?

我写了一个生命游戏控制台应用程序,现在我正在为它编写单元测试。游戏板以循环方式呈现,可以使用 Esc 键中断。但是我不知道如何在我的主应用程序类的测试方法中模拟该按键,所以我的测试当前无限循环。


应用.cs


public class Application

{

    private readonly IGame _game;

    private readonly IBoard _board;

    private readonly IBoardGenerator _boardGenerator;

    private readonly IConsole _console;


    public Application(IGame game, IBoard board, IBoardGenerator boardGenerator, IConsole console)

    {

        _game = game;

        _board = board;

        _boardGenerator = boardGenerator;

        _console = console;

    }

    public void Run()

    {

        void RenderBoard()

        {

            _console.Clear();

            _board.Evolve();

            _board.Print();

            Thread.Sleep(150);

        } 


        LoopUntilButtonPressed(() =>

        { 

            _console.Clear();

            _game.NewGame();

            _game.SetBoard(_board, _boardGenerator);

            LoopUntilButtonPressed(RenderBoard, ConsoleKey.Escape);

        }, ConsoleKey.Escape);

    }


    private void LoopUntilButtonPressed(Action action, ConsoleKey consoleKey)

    {

        do

        {

            while (!_console.KeyAvailable)

            {

                action.Invoke();

            }

        } while (_console.ReadKey(true) != consoleKey);

    }


呼唤远方
浏览 91回答 1
1回答

牛魔王的故事

在控制台抽象上模拟ReadKey和成员。KeyAvailable确保Setup发生在被测方法之前。在这种情况下是Run. 这样,模拟将在调用时按预期运行。我还建议您设置一个序列,KeyAvailable以便在while.[Test]public void Run_MethodCalled_GameCorrectlySet() {&nbsp; &nbsp; //Arrange&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; _fakeConsole.Setup(_ => _.ReadKey(It.IsAny<bool>())).Returns(ConsoleKey.Escape);&nbsp; &nbsp; _fakeConsole.SetupSequence(_ => _.KeyAvailable)&nbsp; &nbsp; &nbsp; &nbsp; .Returns(false) // will be returned on 1st invocation&nbsp; &nbsp; &nbsp; &nbsp; .Returns(true); // will be returned on 2nd invocation to break while&nbsp; &nbsp; //Act&nbsp; &nbsp; _application.Run();&nbsp; &nbsp; //Assert&nbsp; &nbsp; _fakeGame.Verify(_ => _.NewGame(), Times.Once);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP