douzhao7445 2018-12-27 03:47
浏览 49

编写Golang单元测试的功能,该功能期望按键继续

I have a function in Golang something like this:

func Exit(code int) {
    ...
    ...
    ...
    keyboard.Open()
    defer keyboard.Close()
    keyboard.GetKey()
    PrintAndLogInfo("
Bye.")
    os.Exit(code)
}

I am using the following library to use this keyboard feature

github.com/eiannone/keyboard

I would like to write unit tests for this function. However, the keyboard.GetKey() expects a key pressed. And maybe because of that when I run my test that calls the function Exit, it fails with the error:

panic: function GetKey() should be called after Open() [recovered] panic: function GetKey() should be called after Open()

Do I need to mock something here in order to fix this error? Any ideas?

  • 写回答

1条回答 默认 最新

  • douzai9405 2018-12-27 08:20
    关注

    Actually, the error function GetKey() should be called after Open() is triggered by keyboard.GetKey(). It seems GetKey() thinks Open() was never called. Now, in your example, we do see keyboard.Open() - but Open() can actually return an error, which you seem to ignore. So you should check what the error is and deal with that in your code.

    However, that doesn't actually solve your problem - because you probably do not want to press a key every time your unit tests are ran (especially not on your CI environment).

    Like you say, I would mock the keyboard library. That is: write an interface that does the things you need, write an implementation of that interface that simple calls the keyboard library and write a mock implementation to help testing. That mock can then directly return from GetKey() (or whatever you call it in your interface). A more advances mock could have some configuration to return directly, sleep a bit or never return.

    I've created a quick example of how that would work, see https://gist.github.com/jorygeerts/e887856cc15b64cb9681639cd83c4a37. Note that for your tests, you probably also want to inject something to mock os.Exit() and perhaps also your PrintAndLogInfo.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题