You're writing unit tests for a function that should return an error under certain conditions. How would you test this behavior in Go?

  • Check if the error returned is not nil
  • Compare the returned error message to an expected error message
  • Use the testing.T.Error function to fail the test if the error is not returned
  • Use the testing.T.FailNow function to immediately fail the test
In Go, you can test error conditions by comparing the returned error message to an expected error message. This ensures that the function under test behaves as expected when encountering specific error conditions. Simply checking if the error returned is not nil may not provide enough information about the nature of the error. Similarly, using testing.T.Error only reports an error but doesn't validate the specific error returned. Using testing.T.FailNow immediately stops the test, which might not allow you to collect all the error information. Therefore, comparing the returned error message to an expected error message is the most appropriate approach.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *