0

I am building unit testing of the application that uses os.Exit(1), once os.Exit(1) executes remaining test file are skipped with go test, I am thinking about suppressing os.Exit during the unit test execution only. I wonder how I can determine that app has been bootstrap from go test runner?

Adrian
  • 1,973
  • 1
  • 15
  • 28
  • 1
    In general, you're looking for "mocking" APIs. – Jonathon Reinhart Feb 10 '18 at 00:54
  • 1
    Don't add your code in a comment; it's unreadable. Please edit your question and include it properly formatted. – Jonathon Reinhart Feb 10 '18 at 01:02
  • 1
    Don't do that. Your code under test must work 100% the same under test as in production. Otherwise, you're doing an invalid test. If you have a function that exits during production, but not during test, then your code is not organized properly. Move the exit out of the code being tested, so that the tested code works identically in both test and prod environments. – Jonathan Hall Feb 10 '18 at 12:43
  • @Flimzy how do mean do not do that? "Must" is very strong word, explain invalid, it is your opinion? – Adrian Apr 27 '18 at 02:29
  • 1
    @AdrianWitas: If you want to test that a function works in production, you must (there is no other word) test it under the same meaningful conditions. – Jonathan Hall Apr 27 '18 at 13:10

1 Answers1

0

You will find various ways to unit test method with os.Exit() in "Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls)".

It uses a function which is:

  • os.Exit() when you are not testing

    var osExit = os.Exit
    
  • and "yourOsExit" when you are testing.

    func TestCrasher(t *testing.T) {
        // Save current function and restore at the end:
        oldOsExit := osExit
        defer func() { osExit = oldOsExit }()
        osExit = myExit
    
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Can you provide more details? If that link dies, this answer is effectively useless. – Jonathon Reinhart Feb 10 '18 at 01:01
  • 1
    @JonathonReinhart done, but note that link points to another Stack Overflow question: it won't die/rot. – VonC Feb 10 '18 at 01:04
  • @VonC Okay. Why not vote to close this as a duplicate, then? – Jonathon Reinhart Feb 10 '18 at 02:58
  • Various problem may be solved in a various way, the post asks specifically about unit test identification mode, so there is no duplication there, however mocking OsExit might be one easier way to address it ,This solution has been applicable to other problems, thus post submitted. – Adrian Feb 10 '18 at 16:14