Golang Assert
What is Assert in Golang?
Assert is a package that provides a set of helper functions that make it easier to test various properties in your Go programs. It is intended to be used in the xtest files of your package, as an aid in writing tests.
How to use Assert in Golang
Installation
Example
Test file
Output:
Major Assert Methods
1. Equal and NotEqual
assert.Equal()
and assert.NotEqual()
are used to check if the two objects are equal or not. It takes three arguments, the first one is the testing object, the second one is the expected object and the third one is the actual object.
3. Nil and NotNil
assert.Nil()
and assert.NotNil()
are used to check if the object is nil or not. It takes two arguments, the first one is the testing object and the second one is the object to be checked.
5. True and False
assert.True()
and assert.False()
are used to check if the object is true or false, they are both usually used with boolean values or functions returning boolean values. It takes two arguments, the first one is the testing object and the second one is the object to be checked.
6. Empty and NotEmpty
assert.Empty()
and assert.NotEmpty()
are used to check if the object is empty or not. It takes two arguments, the first one is the testing object and the second one is the object to be checked.
7. Len
assert.Len()
is used to check if the length of the object is equal to the expected length. It takes three arguments, the first one is the testing object, the second one is the object to be checked and the third one is the expected length.
8. Contains
assert.Contains()
is used to check if the object contains the expected value. It takes three arguments, the first one is the testing object, the second one is the object to be checked and the third one is the expected value.
9. Panics and NotPanics
assert.Panics()
and assert.NotPanics()
is used to check if the function panics or not. It takes two arguments, the first one is the testing object and the second one is the function to be checked.
10. Error and NoError
assert.Error()
and assert.NoError()
is used to check if the error is nil or not. It takes two arguments, the first one is the testing object and the second one is the error to be checked.
Conclusion
writing tests is a very important part of the development process, and it is very important to write tests for your code. In this article, we have learned how to use the assert package in Golang. We have also learned about the major assert methods. I hope you have enjoyed this article.
Extend your knowledge with these articles:
-
Writting Tests in Golang (A Complete Guide)
- Golang Benchmarking If you have any questions or suggestions, please reach out to me on Twitter.