user1892775
user1892775

Reputation: 2111

write Golang unit test for function that expects a key pressed to continue

I have a function in Golang something like this:

func Exit(code int) {
    ...
    ...
    ...
    keyboard.Open()
    defer keyboard.Close()
    keyboard.GetKey()
    PrintAndLogInfo("\nBye.")
    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?

Upvotes: 0

Views: 530

Answers (1)

Jory Geerts
Jory Geerts

Reputation: 1977

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.

Upvotes: 2

Related Questions