You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

340 lines
10 KiB

  1. Testify - Thou Shalt Write Tests
  2. ================================
  3. [![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify)
  4. Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend.
  5. Features include:
  6. * [Easy assertions](#assert-package)
  7. * [Mocking](#mock-package)
  8. * [Testing suite interfaces and functions](#suite-package)
  9. Get started:
  10. * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date)
  11. * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing
  12. * Check out the API Documentation http://godoc.org/github.com/stretchr/testify
  13. * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc)
  14. * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development)
  15. [`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package
  16. -------------------------------------------------------------------------------------------
  17. The `assert` package provides some helpful methods that allow you to write better test code in Go.
  18. * Prints friendly, easy to read failure descriptions
  19. * Allows for very readable code
  20. * Optionally annotate each assertion with a message
  21. See it in action:
  22. ```go
  23. package yours
  24. import (
  25. "testing"
  26. "github.com/stretchr/testify/assert"
  27. )
  28. func TestSomething(t *testing.T) {
  29. // assert equality
  30. assert.Equal(t, 123, 123, "they should be equal")
  31. // assert inequality
  32. assert.NotEqual(t, 123, 456, "they should not be equal")
  33. // assert for nil (good for errors)
  34. assert.Nil(t, object)
  35. // assert for not nil (good when you expect something)
  36. if assert.NotNil(t, object) {
  37. // now we know that object isn't nil, we are safe to make
  38. // further assertions without causing any errors
  39. assert.Equal(t, "Something", object.Value)
  40. }
  41. }
  42. ```
  43. * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities.
  44. * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions.
  45. if you assert many times, use the below:
  46. ```go
  47. package yours
  48. import (
  49. "testing"
  50. "github.com/stretchr/testify/assert"
  51. )
  52. func TestSomething(t *testing.T) {
  53. assert := assert.New(t)
  54. // assert equality
  55. assert.Equal(123, 123, "they should be equal")
  56. // assert inequality
  57. assert.NotEqual(123, 456, "they should not be equal")
  58. // assert for nil (good for errors)
  59. assert.Nil(object)
  60. // assert for not nil (good when you expect something)
  61. if assert.NotNil(object) {
  62. // now we know that object isn't nil, we are safe to make
  63. // further assertions without causing any errors
  64. assert.Equal("Something", object.Value)
  65. }
  66. }
  67. ```
  68. [`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package
  69. ---------------------------------------------------------------------------------------------
  70. The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test.
  71. See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details.
  72. [`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package
  73. ----------------------------------------------------------------------------------------
  74. The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.
  75. An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened:
  76. ```go
  77. package yours
  78. import (
  79. "testing"
  80. "github.com/stretchr/testify/mock"
  81. )
  82. /*
  83. Test objects
  84. */
  85. // MyMockedObject is a mocked object that implements an interface
  86. // that describes an object that the code I am testing relies on.
  87. type MyMockedObject struct{
  88. mock.Mock
  89. }
  90. // DoSomething is a method on MyMockedObject that implements some interface
  91. // and just records the activity, and returns what the Mock object tells it to.
  92. //
  93. // In the real object, this method would do something useful, but since this
  94. // is a mocked object - we're just going to stub it out.
  95. //
  96. // NOTE: This method is not being tested here, code that uses this object is.
  97. func (m *MyMockedObject) DoSomething(number int) (bool, error) {
  98. args := m.Called(number)
  99. return args.Bool(0), args.Error(1)
  100. }
  101. /*
  102. Actual test functions
  103. */
  104. // TestSomething is an example of how to use our test object to
  105. // make assertions about some target code we are testing.
  106. func TestSomething(t *testing.T) {
  107. // create an instance of our test object
  108. testObj := new(MyMockedObject)
  109. // setup expectations
  110. testObj.On("DoSomething", 123).Return(true, nil)
  111. // call the code we are testing
  112. targetFuncThatDoesSomethingWithObj(testObj)
  113. // assert that the expectations were met
  114. testObj.AssertExpectations(t)
  115. }
  116. // TestSomethingElse is a second example of how to use our test object to
  117. // make assertions about some target code we are testing.
  118. // This time using a placeholder. Placeholders might be used when the
  119. // data being passed in is normally dynamically generated and cannot be
  120. // predicted beforehand (eg. containing hashes that are time sensitive)
  121. func TestSomethingElse(t *testing.T) {
  122. // create an instance of our test object
  123. testObj := new(MyMockedObject)
  124. // setup expectations with a placeholder in the argument list
  125. testObj.On("DoSomething", mock.Anything).Return(true, nil)
  126. // call the code we are testing
  127. targetFuncThatDoesSomethingWithObj(testObj)
  128. // assert that the expectations were met
  129. testObj.AssertExpectations(t)
  130. }
  131. ```
  132. For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock).
  133. You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker.
  134. [`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package
  135. -----------------------------------------------------------------------------------------
  136. The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.
  137. An example suite is shown below:
  138. ```go
  139. // Basic imports
  140. import (
  141. "testing"
  142. "github.com/stretchr/testify/assert"
  143. "github.com/stretchr/testify/suite"
  144. )
  145. // Define the suite, and absorb the built-in basic suite
  146. // functionality from testify - including a T() method which
  147. // returns the current testing context
  148. type ExampleTestSuite struct {
  149. suite.Suite
  150. VariableThatShouldStartAtFive int
  151. }
  152. // Make sure that VariableThatShouldStartAtFive is set to five
  153. // before each test
  154. func (suite *ExampleTestSuite) SetupTest() {
  155. suite.VariableThatShouldStartAtFive = 5
  156. }
  157. // All methods that begin with "Test" are run as tests within a
  158. // suite.
  159. func (suite *ExampleTestSuite) TestExample() {
  160. assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
  161. }
  162. // In order for 'go test' to run this suite, we need to create
  163. // a normal test function and pass our suite to suite.Run
  164. func TestExampleTestSuite(t *testing.T) {
  165. suite.Run(t, new(ExampleTestSuite))
  166. }
  167. ```
  168. For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go)
  169. For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite).
  170. `Suite` object has assertion methods:
  171. ```go
  172. // Basic imports
  173. import (
  174. "testing"
  175. "github.com/stretchr/testify/suite"
  176. )
  177. // Define the suite, and absorb the built-in basic suite
  178. // functionality from testify - including assertion methods.
  179. type ExampleTestSuite struct {
  180. suite.Suite
  181. VariableThatShouldStartAtFive int
  182. }
  183. // Make sure that VariableThatShouldStartAtFive is set to five
  184. // before each test
  185. func (suite *ExampleTestSuite) SetupTest() {
  186. suite.VariableThatShouldStartAtFive = 5
  187. }
  188. // All methods that begin with "Test" are run as tests within a
  189. // suite.
  190. func (suite *ExampleTestSuite) TestExample() {
  191. suite.Equal(suite.VariableThatShouldStartAtFive, 5)
  192. }
  193. // In order for 'go test' to run this suite, we need to create
  194. // a normal test function and pass our suite to suite.Run
  195. func TestExampleTestSuite(t *testing.T) {
  196. suite.Run(t, new(ExampleTestSuite))
  197. }
  198. ```
  199. ------
  200. Installation
  201. ============
  202. To install Testify, use `go get`:
  203. go get github.com/stretchr/testify
  204. This will then make the following packages available to you:
  205. github.com/stretchr/testify/assert
  206. github.com/stretchr/testify/require
  207. github.com/stretchr/testify/mock
  208. github.com/stretchr/testify/suite
  209. github.com/stretchr/testify/http (deprecated)
  210. Import the `testify/assert` package into your code using this template:
  211. ```go
  212. package yours
  213. import (
  214. "testing"
  215. "github.com/stretchr/testify/assert"
  216. )
  217. func TestSomething(t *testing.T) {
  218. assert.True(t, true, "True is true!")
  219. }
  220. ```
  221. ------
  222. Staying up to date
  223. ==================
  224. To update Testify to the latest version, use `go get -u github.com/stretchr/testify`.
  225. ------
  226. Supported go versions
  227. ==================
  228. We support the three major Go versions, which are 1.9, 1.10, and 1.11 at the moment.
  229. ------
  230. Contributing
  231. ============
  232. Please feel free to submit issues, fork the repository and send pull requests!
  233. When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it.
  234. ------
  235. License
  236. =======
  237. This project is licensed under the terms of the MIT license.