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.

1499 lines
41 KiB

  1. package mock
  2. import (
  3. "errors"
  4. "fmt"
  5. "regexp"
  6. "runtime"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. )
  13. /*
  14. Test objects
  15. */
  16. // ExampleInterface represents an example interface.
  17. type ExampleInterface interface {
  18. TheExampleMethod(a, b, c int) (int, error)
  19. }
  20. // TestExampleImplementation is a test implementation of ExampleInterface
  21. type TestExampleImplementation struct {
  22. Mock
  23. }
  24. func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) {
  25. args := i.Called(a, b, c)
  26. return args.Int(0), errors.New("Whoops")
  27. }
  28. //go:noinline
  29. func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) {
  30. i.Called(yesorno)
  31. }
  32. type ExampleType struct {
  33. ran bool
  34. }
  35. func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error {
  36. args := i.Called(et)
  37. return args.Error(0)
  38. }
  39. func (i *TestExampleImplementation) TheExampleMethod4(v ExampleInterface) error {
  40. args := i.Called(v)
  41. return args.Error(0)
  42. }
  43. func (i *TestExampleImplementation) TheExampleMethod5(ch chan struct{}) error {
  44. args := i.Called(ch)
  45. return args.Error(0)
  46. }
  47. func (i *TestExampleImplementation) TheExampleMethod6(m map[string]bool) error {
  48. args := i.Called(m)
  49. return args.Error(0)
  50. }
  51. func (i *TestExampleImplementation) TheExampleMethod7(slice []bool) error {
  52. args := i.Called(slice)
  53. return args.Error(0)
  54. }
  55. func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error {
  56. args := i.Called(fn)
  57. return args.Error(0)
  58. }
  59. func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error {
  60. args := i.Called(a)
  61. return args.Error(0)
  62. }
  63. func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error {
  64. args := i.Called(a)
  65. return args.Error(0)
  66. }
  67. func (i *TestExampleImplementation) TheExampleMethodMixedVariadic(a int, b ...int) error {
  68. args := i.Called(a, b)
  69. return args.Error(0)
  70. }
  71. type ExampleFuncType func(string) error
  72. func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error {
  73. args := i.Called(fn)
  74. return args.Error(0)
  75. }
  76. // MockTestingT mocks a test struct
  77. type MockTestingT struct {
  78. logfCount, errorfCount, failNowCount int
  79. }
  80. const mockTestingTFailNowCalled = "FailNow was called"
  81. func (m *MockTestingT) Logf(string, ...interface{}) {
  82. m.logfCount++
  83. }
  84. func (m *MockTestingT) Errorf(string, ...interface{}) {
  85. m.errorfCount++
  86. }
  87. // FailNow mocks the FailNow call.
  88. // It panics in order to mimic the FailNow behavior in the sense that
  89. // the execution stops.
  90. // When expecting this method, the call that invokes it should use the following code:
  91. //
  92. // assert.PanicsWithValue(t, mockTestingTFailNowCalled, func() {...})
  93. func (m *MockTestingT) FailNow() {
  94. m.failNowCount++
  95. // this function should panic now to stop the execution as expected
  96. panic(mockTestingTFailNowCalled)
  97. }
  98. /*
  99. Mock
  100. */
  101. func Test_Mock_TestData(t *testing.T) {
  102. var mockedService = new(TestExampleImplementation)
  103. if assert.NotNil(t, mockedService.TestData()) {
  104. mockedService.TestData().Set("something", 123)
  105. assert.Equal(t, 123, mockedService.TestData().Get("something").Data())
  106. }
  107. }
  108. func Test_Mock_On(t *testing.T) {
  109. // make a test impl object
  110. var mockedService = new(TestExampleImplementation)
  111. c := mockedService.On("TheExampleMethod")
  112. assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  113. assert.Equal(t, "TheExampleMethod", c.Method)
  114. }
  115. func Test_Mock_Chained_On(t *testing.T) {
  116. // make a test impl object
  117. var mockedService = new(TestExampleImplementation)
  118. // determine our current line number so we can assert the expected calls callerInfo properly
  119. _, _, line, _ := runtime.Caller(0)
  120. mockedService.
  121. On("TheExampleMethod", 1, 2, 3).
  122. Return(0).
  123. On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
  124. Return(nil)
  125. expectedCalls := []*Call{
  126. {
  127. Parent: &mockedService.Mock,
  128. Method: "TheExampleMethod",
  129. Arguments: []interface{}{1, 2, 3},
  130. ReturnArguments: []interface{}{0},
  131. callerInfo: []string{fmt.Sprintf("mock_test.go:%d", line+2)},
  132. },
  133. {
  134. Parent: &mockedService.Mock,
  135. Method: "TheExampleMethod3",
  136. Arguments: []interface{}{AnythingOfType("*mock.ExampleType")},
  137. ReturnArguments: []interface{}{nil},
  138. callerInfo: []string{fmt.Sprintf("mock_test.go:%d", line+4)},
  139. },
  140. }
  141. assert.Equal(t, expectedCalls, mockedService.ExpectedCalls)
  142. }
  143. func Test_Mock_On_WithArgs(t *testing.T) {
  144. // make a test impl object
  145. var mockedService = new(TestExampleImplementation)
  146. c := mockedService.On("TheExampleMethod", 1, 2, 3, 4)
  147. assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  148. assert.Equal(t, "TheExampleMethod", c.Method)
  149. assert.Equal(t, Arguments{1, 2, 3, 4}, c.Arguments)
  150. }
  151. func Test_Mock_On_WithFuncArg(t *testing.T) {
  152. // make a test impl object
  153. var mockedService = new(TestExampleImplementation)
  154. c := mockedService.
  155. On("TheExampleMethodFunc", AnythingOfType("func(string) error")).
  156. Return(nil)
  157. assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  158. assert.Equal(t, "TheExampleMethodFunc", c.Method)
  159. assert.Equal(t, 1, len(c.Arguments))
  160. assert.Equal(t, AnythingOfType("func(string) error"), c.Arguments[0])
  161. fn := func(string) error { return nil }
  162. assert.NotPanics(t, func() {
  163. mockedService.TheExampleMethodFunc(fn)
  164. })
  165. }
  166. func Test_Mock_On_WithIntArgMatcher(t *testing.T) {
  167. var mockedService TestExampleImplementation
  168. mockedService.On("TheExampleMethod",
  169. MatchedBy(func(a int) bool {
  170. return a == 1
  171. }), MatchedBy(func(b int) bool {
  172. return b == 2
  173. }), MatchedBy(func(c int) bool {
  174. return c == 3
  175. })).Return(0, nil)
  176. assert.Panics(t, func() {
  177. mockedService.TheExampleMethod(1, 2, 4)
  178. })
  179. assert.Panics(t, func() {
  180. mockedService.TheExampleMethod(2, 2, 3)
  181. })
  182. assert.NotPanics(t, func() {
  183. mockedService.TheExampleMethod(1, 2, 3)
  184. })
  185. }
  186. func TestMock_WithTest(t *testing.T) {
  187. var (
  188. mockedService TestExampleImplementation
  189. mockedTest MockTestingT
  190. )
  191. mockedService.Test(&mockedTest)
  192. mockedService.On("TheExampleMethod", 1, 2, 3).Return(0, nil)
  193. // Test that on an expected call, the test was not failed
  194. mockedService.TheExampleMethod(1, 2, 3)
  195. // Assert that Errorf and FailNow were not called
  196. assert.Equal(t, 0, mockedTest.errorfCount)
  197. assert.Equal(t, 0, mockedTest.failNowCount)
  198. // Test that on unexpected call, the mocked test was called to fail the test
  199. assert.PanicsWithValue(t, mockTestingTFailNowCalled, func() {
  200. mockedService.TheExampleMethod(1, 1, 1)
  201. })
  202. // Assert that Errorf and FailNow were called once
  203. assert.Equal(t, 1, mockedTest.errorfCount)
  204. assert.Equal(t, 1, mockedTest.failNowCount)
  205. }
  206. func Test_Mock_On_WithPtrArgMatcher(t *testing.T) {
  207. var mockedService TestExampleImplementation
  208. mockedService.On("TheExampleMethod3",
  209. MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == true }),
  210. ).Return(nil)
  211. mockedService.On("TheExampleMethod3",
  212. MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == false }),
  213. ).Return(errors.New("error"))
  214. mockedService.On("TheExampleMethod3",
  215. MatchedBy(func(a *ExampleType) bool { return a == nil }),
  216. ).Return(errors.New("error2"))
  217. assert.Equal(t, mockedService.TheExampleMethod3(&ExampleType{true}), nil)
  218. assert.EqualError(t, mockedService.TheExampleMethod3(&ExampleType{false}), "error")
  219. assert.EqualError(t, mockedService.TheExampleMethod3(nil), "error2")
  220. }
  221. func Test_Mock_On_WithFuncArgMatcher(t *testing.T) {
  222. var mockedService TestExampleImplementation
  223. fixture1, fixture2 := errors.New("fixture1"), errors.New("fixture2")
  224. mockedService.On("TheExampleMethodFunc",
  225. MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture1 }),
  226. ).Return(errors.New("fixture1"))
  227. mockedService.On("TheExampleMethodFunc",
  228. MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture2 }),
  229. ).Return(errors.New("fixture2"))
  230. mockedService.On("TheExampleMethodFunc",
  231. MatchedBy(func(a func(string) error) bool { return a == nil }),
  232. ).Return(errors.New("fixture3"))
  233. assert.EqualError(t, mockedService.TheExampleMethodFunc(
  234. func(string) error { return fixture1 }), "fixture1")
  235. assert.EqualError(t, mockedService.TheExampleMethodFunc(
  236. func(string) error { return fixture2 }), "fixture2")
  237. assert.EqualError(t, mockedService.TheExampleMethodFunc(nil), "fixture3")
  238. }
  239. func Test_Mock_On_WithInterfaceArgMatcher(t *testing.T) {
  240. var mockedService TestExampleImplementation
  241. mockedService.On("TheExampleMethod4",
  242. MatchedBy(func(a ExampleInterface) bool { return a == nil }),
  243. ).Return(errors.New("fixture1"))
  244. assert.EqualError(t, mockedService.TheExampleMethod4(nil), "fixture1")
  245. }
  246. func Test_Mock_On_WithChannelArgMatcher(t *testing.T) {
  247. var mockedService TestExampleImplementation
  248. mockedService.On("TheExampleMethod5",
  249. MatchedBy(func(ch chan struct{}) bool { return ch == nil }),
  250. ).Return(errors.New("fixture1"))
  251. assert.EqualError(t, mockedService.TheExampleMethod5(nil), "fixture1")
  252. }
  253. func Test_Mock_On_WithMapArgMatcher(t *testing.T) {
  254. var mockedService TestExampleImplementation
  255. mockedService.On("TheExampleMethod6",
  256. MatchedBy(func(m map[string]bool) bool { return m == nil }),
  257. ).Return(errors.New("fixture1"))
  258. assert.EqualError(t, mockedService.TheExampleMethod6(nil), "fixture1")
  259. }
  260. func Test_Mock_On_WithSliceArgMatcher(t *testing.T) {
  261. var mockedService TestExampleImplementation
  262. mockedService.On("TheExampleMethod7",
  263. MatchedBy(func(slice []bool) bool { return slice == nil }),
  264. ).Return(errors.New("fixture1"))
  265. assert.EqualError(t, mockedService.TheExampleMethod7(nil), "fixture1")
  266. }
  267. func Test_Mock_On_WithVariadicFunc(t *testing.T) {
  268. // make a test impl object
  269. var mockedService = new(TestExampleImplementation)
  270. c := mockedService.
  271. On("TheExampleMethodVariadic", []int{1, 2, 3}).
  272. Return(nil)
  273. assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  274. assert.Equal(t, 1, len(c.Arguments))
  275. assert.Equal(t, []int{1, 2, 3}, c.Arguments[0])
  276. assert.NotPanics(t, func() {
  277. mockedService.TheExampleMethodVariadic(1, 2, 3)
  278. })
  279. assert.Panics(t, func() {
  280. mockedService.TheExampleMethodVariadic(1, 2)
  281. })
  282. }
  283. func Test_Mock_On_WithMixedVariadicFunc(t *testing.T) {
  284. // make a test impl object
  285. var mockedService = new(TestExampleImplementation)
  286. c := mockedService.
  287. On("TheExampleMethodMixedVariadic", 1, []int{2, 3, 4}).
  288. Return(nil)
  289. assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  290. assert.Equal(t, 2, len(c.Arguments))
  291. assert.Equal(t, 1, c.Arguments[0])
  292. assert.Equal(t, []int{2, 3, 4}, c.Arguments[1])
  293. assert.NotPanics(t, func() {
  294. mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 4)
  295. })
  296. assert.Panics(t, func() {
  297. mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 5)
  298. })
  299. }
  300. func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) {
  301. // make a test impl object
  302. var mockedService = new(TestExampleImplementation)
  303. c := mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}).
  304. Return(nil)
  305. assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  306. assert.Equal(t, 1, len(c.Arguments))
  307. assert.Equal(t, []interface{}{1, 2, 3}, c.Arguments[0])
  308. assert.NotPanics(t, func() {
  309. mockedService.TheExampleMethodVariadicInterface(1, 2, 3)
  310. })
  311. assert.Panics(t, func() {
  312. mockedService.TheExampleMethodVariadicInterface(1, 2)
  313. })
  314. }
  315. func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) {
  316. // make a test impl object
  317. var mockedService = new(TestExampleImplementation)
  318. var expected []interface{}
  319. c := mockedService.
  320. On("TheExampleMethodVariadicInterface", expected).
  321. Return(nil)
  322. assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  323. assert.Equal(t, 1, len(c.Arguments))
  324. assert.Equal(t, expected, c.Arguments[0])
  325. assert.NotPanics(t, func() {
  326. mockedService.TheExampleMethodVariadicInterface()
  327. })
  328. assert.Panics(t, func() {
  329. mockedService.TheExampleMethodVariadicInterface(1, 2)
  330. })
  331. }
  332. func Test_Mock_On_WithFuncPanics(t *testing.T) {
  333. // make a test impl object
  334. var mockedService = new(TestExampleImplementation)
  335. assert.Panics(t, func() {
  336. mockedService.On("TheExampleMethodFunc", func(string) error { return nil })
  337. })
  338. }
  339. func Test_Mock_On_WithFuncTypeArg(t *testing.T) {
  340. // make a test impl object
  341. var mockedService = new(TestExampleImplementation)
  342. c := mockedService.
  343. On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")).
  344. Return(nil)
  345. assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  346. assert.Equal(t, 1, len(c.Arguments))
  347. assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), c.Arguments[0])
  348. fn := func(string) error { return nil }
  349. assert.NotPanics(t, func() {
  350. mockedService.TheExampleMethodFuncType(fn)
  351. })
  352. }
  353. func Test_Mock_Return(t *testing.T) {
  354. // make a test impl object
  355. var mockedService = new(TestExampleImplementation)
  356. c := mockedService.
  357. On("TheExampleMethod", "A", "B", true).
  358. Return(1, "two", true)
  359. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  360. call := mockedService.ExpectedCalls[0]
  361. assert.Equal(t, "TheExampleMethod", call.Method)
  362. assert.Equal(t, "A", call.Arguments[0])
  363. assert.Equal(t, "B", call.Arguments[1])
  364. assert.Equal(t, true, call.Arguments[2])
  365. assert.Equal(t, 1, call.ReturnArguments[0])
  366. assert.Equal(t, "two", call.ReturnArguments[1])
  367. assert.Equal(t, true, call.ReturnArguments[2])
  368. assert.Equal(t, 0, call.Repeatability)
  369. assert.Nil(t, call.WaitFor)
  370. }
  371. func Test_Mock_Return_WaitUntil(t *testing.T) {
  372. // make a test impl object
  373. var mockedService = new(TestExampleImplementation)
  374. ch := time.After(time.Second)
  375. c := mockedService.Mock.
  376. On("TheExampleMethod", "A", "B", true).
  377. WaitUntil(ch).
  378. Return(1, "two", true)
  379. // assert that the call was created
  380. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  381. call := mockedService.ExpectedCalls[0]
  382. assert.Equal(t, "TheExampleMethod", call.Method)
  383. assert.Equal(t, "A", call.Arguments[0])
  384. assert.Equal(t, "B", call.Arguments[1])
  385. assert.Equal(t, true, call.Arguments[2])
  386. assert.Equal(t, 1, call.ReturnArguments[0])
  387. assert.Equal(t, "two", call.ReturnArguments[1])
  388. assert.Equal(t, true, call.ReturnArguments[2])
  389. assert.Equal(t, 0, call.Repeatability)
  390. assert.Equal(t, ch, call.WaitFor)
  391. }
  392. func Test_Mock_Return_After(t *testing.T) {
  393. // make a test impl object
  394. var mockedService = new(TestExampleImplementation)
  395. c := mockedService.Mock.
  396. On("TheExampleMethod", "A", "B", true).
  397. Return(1, "two", true).
  398. After(time.Second)
  399. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  400. call := mockedService.Mock.ExpectedCalls[0]
  401. assert.Equal(t, "TheExampleMethod", call.Method)
  402. assert.Equal(t, "A", call.Arguments[0])
  403. assert.Equal(t, "B", call.Arguments[1])
  404. assert.Equal(t, true, call.Arguments[2])
  405. assert.Equal(t, 1, call.ReturnArguments[0])
  406. assert.Equal(t, "two", call.ReturnArguments[1])
  407. assert.Equal(t, true, call.ReturnArguments[2])
  408. assert.Equal(t, 0, call.Repeatability)
  409. assert.NotEqual(t, nil, call.WaitFor)
  410. }
  411. func Test_Mock_Return_Run(t *testing.T) {
  412. // make a test impl object
  413. var mockedService = new(TestExampleImplementation)
  414. fn := func(args Arguments) {
  415. arg := args.Get(0).(*ExampleType)
  416. arg.ran = true
  417. }
  418. c := mockedService.Mock.
  419. On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
  420. Return(nil).
  421. Run(fn)
  422. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  423. call := mockedService.Mock.ExpectedCalls[0]
  424. assert.Equal(t, "TheExampleMethod3", call.Method)
  425. assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0])
  426. assert.Equal(t, nil, call.ReturnArguments[0])
  427. assert.Equal(t, 0, call.Repeatability)
  428. assert.NotEqual(t, nil, call.WaitFor)
  429. assert.NotNil(t, call.Run)
  430. et := ExampleType{}
  431. assert.Equal(t, false, et.ran)
  432. mockedService.TheExampleMethod3(&et)
  433. assert.Equal(t, true, et.ran)
  434. }
  435. func Test_Mock_Return_Run_Out_Of_Order(t *testing.T) {
  436. // make a test impl object
  437. var mockedService = new(TestExampleImplementation)
  438. f := func(args Arguments) {
  439. arg := args.Get(0).(*ExampleType)
  440. arg.ran = true
  441. }
  442. c := mockedService.Mock.
  443. On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
  444. Run(f).
  445. Return(nil)
  446. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  447. call := mockedService.Mock.ExpectedCalls[0]
  448. assert.Equal(t, "TheExampleMethod3", call.Method)
  449. assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0])
  450. assert.Equal(t, nil, call.ReturnArguments[0])
  451. assert.Equal(t, 0, call.Repeatability)
  452. assert.NotEqual(t, nil, call.WaitFor)
  453. assert.NotNil(t, call.Run)
  454. }
  455. func Test_Mock_Return_Once(t *testing.T) {
  456. // make a test impl object
  457. var mockedService = new(TestExampleImplementation)
  458. c := mockedService.On("TheExampleMethod", "A", "B", true).
  459. Return(1, "two", true).
  460. Once()
  461. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  462. call := mockedService.ExpectedCalls[0]
  463. assert.Equal(t, "TheExampleMethod", call.Method)
  464. assert.Equal(t, "A", call.Arguments[0])
  465. assert.Equal(t, "B", call.Arguments[1])
  466. assert.Equal(t, true, call.Arguments[2])
  467. assert.Equal(t, 1, call.ReturnArguments[0])
  468. assert.Equal(t, "two", call.ReturnArguments[1])
  469. assert.Equal(t, true, call.ReturnArguments[2])
  470. assert.Equal(t, 1, call.Repeatability)
  471. assert.Nil(t, call.WaitFor)
  472. }
  473. func Test_Mock_Return_Twice(t *testing.T) {
  474. // make a test impl object
  475. var mockedService = new(TestExampleImplementation)
  476. c := mockedService.
  477. On("TheExampleMethod", "A", "B", true).
  478. Return(1, "two", true).
  479. Twice()
  480. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  481. call := mockedService.ExpectedCalls[0]
  482. assert.Equal(t, "TheExampleMethod", call.Method)
  483. assert.Equal(t, "A", call.Arguments[0])
  484. assert.Equal(t, "B", call.Arguments[1])
  485. assert.Equal(t, true, call.Arguments[2])
  486. assert.Equal(t, 1, call.ReturnArguments[0])
  487. assert.Equal(t, "two", call.ReturnArguments[1])
  488. assert.Equal(t, true, call.ReturnArguments[2])
  489. assert.Equal(t, 2, call.Repeatability)
  490. assert.Nil(t, call.WaitFor)
  491. }
  492. func Test_Mock_Return_Times(t *testing.T) {
  493. // make a test impl object
  494. var mockedService = new(TestExampleImplementation)
  495. c := mockedService.
  496. On("TheExampleMethod", "A", "B", true).
  497. Return(1, "two", true).
  498. Times(5)
  499. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  500. call := mockedService.ExpectedCalls[0]
  501. assert.Equal(t, "TheExampleMethod", call.Method)
  502. assert.Equal(t, "A", call.Arguments[0])
  503. assert.Equal(t, "B", call.Arguments[1])
  504. assert.Equal(t, true, call.Arguments[2])
  505. assert.Equal(t, 1, call.ReturnArguments[0])
  506. assert.Equal(t, "two", call.ReturnArguments[1])
  507. assert.Equal(t, true, call.ReturnArguments[2])
  508. assert.Equal(t, 5, call.Repeatability)
  509. assert.Nil(t, call.WaitFor)
  510. }
  511. func Test_Mock_Return_Nothing(t *testing.T) {
  512. // make a test impl object
  513. var mockedService = new(TestExampleImplementation)
  514. c := mockedService.
  515. On("TheExampleMethod", "A", "B", true).
  516. Return()
  517. require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
  518. call := mockedService.ExpectedCalls[0]
  519. assert.Equal(t, "TheExampleMethod", call.Method)
  520. assert.Equal(t, "A", call.Arguments[0])
  521. assert.Equal(t, "B", call.Arguments[1])
  522. assert.Equal(t, true, call.Arguments[2])
  523. assert.Equal(t, 0, len(call.ReturnArguments))
  524. }
  525. func Test_Mock_findExpectedCall(t *testing.T) {
  526. m := new(Mock)
  527. m.On("One", 1).Return("one")
  528. m.On("Two", 2).Return("two")
  529. m.On("Two", 3).Return("three")
  530. f, c := m.findExpectedCall("Two", 3)
  531. if assert.Equal(t, 2, f) {
  532. if assert.NotNil(t, c) {
  533. assert.Equal(t, "Two", c.Method)
  534. assert.Equal(t, 3, c.Arguments[0])
  535. assert.Equal(t, "three", c.ReturnArguments[0])
  536. }
  537. }
  538. }
  539. func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) {
  540. m := new(Mock)
  541. m.On("One", 1).Return("one")
  542. m.On("Two", 2).Return("two")
  543. m.On("Two", 3).Return("three")
  544. f, _ := m.findExpectedCall("Two")
  545. assert.Equal(t, -1, f)
  546. }
  547. func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) {
  548. m := new(Mock)
  549. m.On("One", 1).Return("one")
  550. m.On("Two", 2).Return("two").Once()
  551. m.On("Two", 3).Return("three").Twice()
  552. m.On("Two", 3).Return("three").Times(8)
  553. f, c := m.findExpectedCall("Two", 3)
  554. if assert.Equal(t, 2, f) {
  555. if assert.NotNil(t, c) {
  556. assert.Equal(t, "Two", c.Method)
  557. assert.Equal(t, 3, c.Arguments[0])
  558. assert.Equal(t, "three", c.ReturnArguments[0])
  559. }
  560. }
  561. }
  562. func Test_callString(t *testing.T) {
  563. assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false))
  564. }
  565. func Test_Mock_Called(t *testing.T) {
  566. var mockedService = new(TestExampleImplementation)
  567. mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true)
  568. returnArguments := mockedService.Called(1, 2, 3)
  569. if assert.Equal(t, 1, len(mockedService.Calls)) {
  570. assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method)
  571. assert.Equal(t, 1, mockedService.Calls[0].Arguments[0])
  572. assert.Equal(t, 2, mockedService.Calls[0].Arguments[1])
  573. assert.Equal(t, 3, mockedService.Calls[0].Arguments[2])
  574. }
  575. if assert.Equal(t, 3, len(returnArguments)) {
  576. assert.Equal(t, 5, returnArguments[0])
  577. assert.Equal(t, "6", returnArguments[1])
  578. assert.Equal(t, true, returnArguments[2])
  579. }
  580. }
  581. func asyncCall(m *Mock, ch chan Arguments) {
  582. ch <- m.Called(1, 2, 3)
  583. }
  584. func Test_Mock_Called_blocks(t *testing.T) {
  585. var mockedService = new(TestExampleImplementation)
  586. mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond)
  587. ch := make(chan Arguments)
  588. go asyncCall(&mockedService.Mock, ch)
  589. select {
  590. case <-ch:
  591. t.Fatal("should have waited")
  592. case <-time.After(1 * time.Millisecond):
  593. }
  594. returnArguments := <-ch
  595. if assert.Equal(t, 1, len(mockedService.Mock.Calls)) {
  596. assert.Equal(t, "asyncCall", mockedService.Mock.Calls[0].Method)
  597. assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0])
  598. assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1])
  599. assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2])
  600. }
  601. if assert.Equal(t, 3, len(returnArguments)) {
  602. assert.Equal(t, 5, returnArguments[0])
  603. assert.Equal(t, "6", returnArguments[1])
  604. assert.Equal(t, true, returnArguments[2])
  605. }
  606. }
  607. func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) {
  608. var mockedService = new(TestExampleImplementation)
  609. mockedService.
  610. On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).
  611. Return(5, "6", true).
  612. Once()
  613. mockedService.
  614. On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).
  615. Return(-1, "hi", false)
  616. returnArguments1 := mockedService.Called(1, 2, 3)
  617. returnArguments2 := mockedService.Called(1, 2, 3)
  618. if assert.Equal(t, 2, len(mockedService.Calls)) {
  619. assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method)
  620. assert.Equal(t, 1, mockedService.Calls[0].Arguments[0])
  621. assert.Equal(t, 2, mockedService.Calls[0].Arguments[1])
  622. assert.Equal(t, 3, mockedService.Calls[0].Arguments[2])
  623. assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method)
  624. assert.Equal(t, 1, mockedService.Calls[1].Arguments[0])
  625. assert.Equal(t, 2, mockedService.Calls[1].Arguments[1])
  626. assert.Equal(t, 3, mockedService.Calls[1].Arguments[2])
  627. }
  628. if assert.Equal(t, 3, len(returnArguments1)) {
  629. assert.Equal(t, 5, returnArguments1[0])
  630. assert.Equal(t, "6", returnArguments1[1])
  631. assert.Equal(t, true, returnArguments1[2])
  632. }
  633. if assert.Equal(t, 3, len(returnArguments2)) {
  634. assert.Equal(t, -1, returnArguments2[0])
  635. assert.Equal(t, "hi", returnArguments2[1])
  636. assert.Equal(t, false, returnArguments2[2])
  637. }
  638. }
  639. func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) {
  640. var mockedService = new(TestExampleImplementation)
  641. mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4)
  642. mockedService.TheExampleMethod(1, 2, 3)
  643. mockedService.TheExampleMethod(1, 2, 3)
  644. mockedService.TheExampleMethod(1, 2, 3)
  645. mockedService.TheExampleMethod(1, 2, 3)
  646. assert.Panics(t, func() {
  647. mockedService.TheExampleMethod(1, 2, 3)
  648. })
  649. }
  650. func Test_Mock_Called_Unexpected(t *testing.T) {
  651. var mockedService = new(TestExampleImplementation)
  652. // make sure it panics if no expectation was made
  653. assert.Panics(t, func() {
  654. mockedService.Called(1, 2, 3)
  655. }, "Calling unexpected method should panic")
  656. }
  657. func Test_AssertExpectationsForObjects_Helper(t *testing.T) {
  658. var mockedService1 = new(TestExampleImplementation)
  659. var mockedService2 = new(TestExampleImplementation)
  660. var mockedService3 = new(TestExampleImplementation)
  661. mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return()
  662. mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return()
  663. mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return()
  664. mockedService1.Called(1)
  665. mockedService2.Called(2)
  666. mockedService3.Called(3)
  667. assert.True(t, AssertExpectationsForObjects(t, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock))
  668. assert.True(t, AssertExpectationsForObjects(t, mockedService1, mockedService2, mockedService3))
  669. }
  670. func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) {
  671. var mockedService1 = new(TestExampleImplementation)
  672. var mockedService2 = new(TestExampleImplementation)
  673. var mockedService3 = new(TestExampleImplementation)
  674. mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return()
  675. mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return()
  676. mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return()
  677. mockedService1.Called(1)
  678. mockedService3.Called(3)
  679. tt := new(testing.T)
  680. assert.False(t, AssertExpectationsForObjects(tt, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock))
  681. assert.False(t, AssertExpectationsForObjects(tt, mockedService1, mockedService2, mockedService3))
  682. }
  683. func Test_Mock_AssertExpectations(t *testing.T) {
  684. var mockedService = new(TestExampleImplementation)
  685. mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7)
  686. tt := new(testing.T)
  687. assert.False(t, mockedService.AssertExpectations(tt))
  688. // make the call now
  689. mockedService.Called(1, 2, 3)
  690. // now assert expectations
  691. assert.True(t, mockedService.AssertExpectations(tt))
  692. }
  693. func Test_Mock_AssertExpectations_Placeholder_NoArgs(t *testing.T) {
  694. var mockedService = new(TestExampleImplementation)
  695. mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(5, 6, 7).Once()
  696. mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(7, 6, 5)
  697. tt := new(testing.T)
  698. assert.False(t, mockedService.AssertExpectations(tt))
  699. // make the call now
  700. mockedService.Called()
  701. // now assert expectations
  702. assert.True(t, mockedService.AssertExpectations(tt))
  703. }
  704. func Test_Mock_AssertExpectations_Placeholder(t *testing.T) {
  705. var mockedService = new(TestExampleImplementation)
  706. mockedService.On("Test_Mock_AssertExpectations_Placeholder", 1, 2, 3).Return(5, 6, 7).Once()
  707. mockedService.On("Test_Mock_AssertExpectations_Placeholder", 3, 2, 1).Return(7, 6, 5)
  708. tt := new(testing.T)
  709. assert.False(t, mockedService.AssertExpectations(tt))
  710. // make the call now
  711. mockedService.Called(1, 2, 3)
  712. // now assert expectations
  713. assert.False(t, mockedService.AssertExpectations(tt))
  714. // make call to the second expectation
  715. mockedService.Called(3, 2, 1)
  716. // now assert expectations again
  717. assert.True(t, mockedService.AssertExpectations(tt))
  718. }
  719. func Test_Mock_AssertExpectations_With_Pointers(t *testing.T) {
  720. var mockedService = new(TestExampleImplementation)
  721. mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{1}).Return(1)
  722. mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{2}).Return(2)
  723. tt := new(testing.T)
  724. assert.False(t, mockedService.AssertExpectations(tt))
  725. s := struct{ Foo int }{1}
  726. // make the calls now
  727. mockedService.Called(&s)
  728. s.Foo = 2
  729. mockedService.Called(&s)
  730. // now assert expectations
  731. assert.True(t, mockedService.AssertExpectations(tt))
  732. }
  733. func Test_Mock_AssertExpectationsCustomType(t *testing.T) {
  734. var mockedService = new(TestExampleImplementation)
  735. mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once()
  736. tt := new(testing.T)
  737. assert.False(t, mockedService.AssertExpectations(tt))
  738. // make the call now
  739. mockedService.TheExampleMethod3(&ExampleType{})
  740. // now assert expectations
  741. assert.True(t, mockedService.AssertExpectations(tt))
  742. }
  743. func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) {
  744. var mockedService = new(TestExampleImplementation)
  745. mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice()
  746. tt := new(testing.T)
  747. assert.False(t, mockedService.AssertExpectations(tt))
  748. // make the call now
  749. mockedService.Called(1, 2, 3)
  750. assert.False(t, mockedService.AssertExpectations(tt))
  751. mockedService.Called(1, 2, 3)
  752. // now assert expectations
  753. assert.True(t, mockedService.AssertExpectations(tt))
  754. }
  755. func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) {
  756. var mockedService = new(TestExampleImplementation)
  757. mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7)
  758. mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7)
  759. args1 := mockedService.Called(1, 2, 3)
  760. assert.Equal(t, 5, args1.Int(0))
  761. assert.Equal(t, 6, args1.Int(1))
  762. assert.Equal(t, 7, args1.Int(2))
  763. args2 := mockedService.Called(4, 5, 6)
  764. assert.Equal(t, 5, args2.Int(0))
  765. assert.Equal(t, 6, args2.Int(1))
  766. assert.Equal(t, 7, args2.Int(2))
  767. }
  768. func Test_Mock_AssertNumberOfCalls(t *testing.T) {
  769. var mockedService = new(TestExampleImplementation)
  770. mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7)
  771. mockedService.Called(1, 2, 3)
  772. assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1))
  773. mockedService.Called(1, 2, 3)
  774. assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2))
  775. }
  776. func Test_Mock_AssertCalled(t *testing.T) {
  777. var mockedService = new(TestExampleImplementation)
  778. mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7)
  779. mockedService.Called(1, 2, 3)
  780. assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3))
  781. }
  782. func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) {
  783. var mockedService = new(TestExampleImplementation)
  784. mockedService.
  785. On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything).
  786. Return()
  787. mockedService.Called(1, "two", []uint8("three"))
  788. assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8")))
  789. }
  790. func Test_Mock_AssertCalled_WithArguments(t *testing.T) {
  791. var mockedService = new(TestExampleImplementation)
  792. mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7)
  793. mockedService.Called(1, 2, 3)
  794. tt := new(testing.T)
  795. assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3))
  796. assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4))
  797. }
  798. func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) {
  799. var mockedService = new(TestExampleImplementation)
  800. mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once()
  801. mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once()
  802. mockedService.Called(1, 2, 3)
  803. mockedService.Called(2, 3, 4)
  804. tt := new(testing.T)
  805. assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3))
  806. assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4))
  807. assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5))
  808. }
  809. func Test_Mock_AssertNotCalled(t *testing.T) {
  810. var mockedService = new(TestExampleImplementation)
  811. mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7)
  812. mockedService.Called(1, 2, 3)
  813. assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled"))
  814. }
  815. func Test_Mock_AssertOptional(t *testing.T) {
  816. // Optional called
  817. var ms1 = new(TestExampleImplementation)
  818. ms1.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil)
  819. ms1.TheExampleMethod(1, 2, 3)
  820. tt1 := new(testing.T)
  821. assert.Equal(t, true, ms1.AssertExpectations(tt1))
  822. // Optional not called
  823. var ms2 = new(TestExampleImplementation)
  824. ms2.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil)
  825. tt2 := new(testing.T)
  826. assert.Equal(t, true, ms2.AssertExpectations(tt2))
  827. // Non-optional called
  828. var ms3 = new(TestExampleImplementation)
  829. ms3.On("TheExampleMethod", 1, 2, 3).Return(4, nil)
  830. ms3.TheExampleMethod(1, 2, 3)
  831. tt3 := new(testing.T)
  832. assert.Equal(t, true, ms3.AssertExpectations(tt3))
  833. }
  834. /*
  835. Arguments helper methods
  836. */
  837. func Test_Arguments_Get(t *testing.T) {
  838. var args = Arguments([]interface{}{"string", 123, true})
  839. assert.Equal(t, "string", args.Get(0).(string))
  840. assert.Equal(t, 123, args.Get(1).(int))
  841. assert.Equal(t, true, args.Get(2).(bool))
  842. }
  843. func Test_Arguments_Is(t *testing.T) {
  844. var args = Arguments([]interface{}{"string", 123, true})
  845. assert.True(t, args.Is("string", 123, true))
  846. assert.False(t, args.Is("wrong", 456, false))
  847. }
  848. func Test_Arguments_Diff(t *testing.T) {
  849. var args = Arguments([]interface{}{"Hello World", 123, true})
  850. var diff string
  851. var count int
  852. diff, count = args.Diff([]interface{}{"Hello World", 456, "false"})
  853. assert.Equal(t, 2, count)
  854. assert.Contains(t, diff, `(int=456) != (int=123)`)
  855. assert.Contains(t, diff, `(string=false) != (bool=true)`)
  856. }
  857. func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) {
  858. var args = Arguments([]interface{}{"string", 123, true})
  859. var diff string
  860. var count int
  861. diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"})
  862. assert.Equal(t, 3, count)
  863. assert.Contains(t, diff, `(string=extra) != (Missing)`)
  864. }
  865. func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) {
  866. var args = Arguments([]interface{}{"string", 123, true})
  867. var count int
  868. _, count = args.Diff([]interface{}{"string", Anything, true})
  869. assert.Equal(t, 0, count)
  870. }
  871. func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) {
  872. var args = Arguments([]interface{}{"string", Anything, true})
  873. var count int
  874. _, count = args.Diff([]interface{}{"string", 123, true})
  875. assert.Equal(t, 0, count)
  876. }
  877. func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) {
  878. var args = Arguments([]interface{}{"string", AnythingOfType("int"), true})
  879. var count int
  880. _, count = args.Diff([]interface{}{"string", 123, true})
  881. assert.Equal(t, 0, count)
  882. }
  883. func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) {
  884. var args = Arguments([]interface{}{"string", AnythingOfType("string"), true})
  885. var count int
  886. var diff string
  887. diff, count = args.Diff([]interface{}{"string", 123, true})
  888. assert.Equal(t, 1, count)
  889. assert.Contains(t, diff, `string != type int - (int=123)`)
  890. }
  891. func Test_Arguments_Diff_WithArgMatcher(t *testing.T) {
  892. matchFn := func(a int) bool {
  893. return a == 123
  894. }
  895. var args = Arguments([]interface{}{"string", MatchedBy(matchFn), true})
  896. diff, count := args.Diff([]interface{}{"string", 124, true})
  897. assert.Equal(t, 1, count)
  898. assert.Contains(t, diff, `(int=124) not matched by func(int) bool`)
  899. diff, count = args.Diff([]interface{}{"string", false, true})
  900. assert.Equal(t, 1, count)
  901. assert.Contains(t, diff, `(bool=false) not matched by func(int) bool`)
  902. diff, count = args.Diff([]interface{}{"string", 123, false})
  903. assert.Contains(t, diff, `(int=123) matched by func(int) bool`)
  904. diff, count = args.Diff([]interface{}{"string", 123, true})
  905. assert.Equal(t, 0, count)
  906. assert.Contains(t, diff, `No differences.`)
  907. }
  908. func Test_Arguments_Assert(t *testing.T) {
  909. var args = Arguments([]interface{}{"string", 123, true})
  910. assert.True(t, args.Assert(t, "string", 123, true))
  911. }
  912. func Test_Arguments_String_Representation(t *testing.T) {
  913. var args = Arguments([]interface{}{"string", 123, true})
  914. assert.Equal(t, `string,int,bool`, args.String())
  915. }
  916. func Test_Arguments_String(t *testing.T) {
  917. var args = Arguments([]interface{}{"string", 123, true})
  918. assert.Equal(t, "string", args.String(0))
  919. }
  920. func Test_Arguments_Error(t *testing.T) {
  921. var err = errors.New("An Error")
  922. var args = Arguments([]interface{}{"string", 123, true, err})
  923. assert.Equal(t, err, args.Error(3))
  924. }
  925. func Test_Arguments_Error_Nil(t *testing.T) {
  926. var args = Arguments([]interface{}{"string", 123, true, nil})
  927. assert.Equal(t, nil, args.Error(3))
  928. }
  929. func Test_Arguments_Int(t *testing.T) {
  930. var args = Arguments([]interface{}{"string", 123, true})
  931. assert.Equal(t, 123, args.Int(1))
  932. }
  933. func Test_Arguments_Bool(t *testing.T) {
  934. var args = Arguments([]interface{}{"string", 123, true})
  935. assert.Equal(t, true, args.Bool(2))
  936. }
  937. func Test_WaitUntil_Parallel(t *testing.T) {
  938. // make a test impl object
  939. var mockedService = new(TestExampleImplementation)
  940. ch1 := make(chan time.Time)
  941. ch2 := make(chan time.Time)
  942. mockedService.Mock.On("TheExampleMethod2", true).Return().WaitUntil(ch2).Run(func(args Arguments) {
  943. ch1 <- time.Now()
  944. })
  945. mockedService.Mock.On("TheExampleMethod2", false).Return().WaitUntil(ch1)
  946. // Lock both goroutines on the .WaitUntil method
  947. go func() {
  948. mockedService.TheExampleMethod2(false)
  949. }()
  950. go func() {
  951. mockedService.TheExampleMethod2(true)
  952. }()
  953. // Allow the first call to execute, so the second one executes afterwards
  954. ch2 <- time.Now()
  955. }
  956. func Test_MockMethodCalled(t *testing.T) {
  957. m := new(Mock)
  958. m.On("foo", "hello").Return("world")
  959. retArgs := m.MethodCalled("foo", "hello")
  960. require.True(t, len(retArgs) == 1)
  961. require.Equal(t, "world", retArgs[0])
  962. m.AssertExpectations(t)
  963. }
  964. // Test to validate fix for racy concurrent call access in MethodCalled()
  965. func Test_MockReturnAndCalledConcurrent(t *testing.T) {
  966. iterations := 1000
  967. m := &Mock{}
  968. call := m.On("ConcurrencyTestMethod")
  969. wg := sync.WaitGroup{}
  970. wg.Add(2)
  971. go func() {
  972. for i := 0; i < iterations; i++ {
  973. call.Return(10)
  974. }
  975. wg.Done()
  976. }()
  977. go func() {
  978. for i := 0; i < iterations; i++ {
  979. ConcurrencyTestMethod(m)
  980. }
  981. wg.Done()
  982. }()
  983. wg.Wait()
  984. }
  985. type timer struct{ Mock }
  986. func (s *timer) GetTime(i int) string {
  987. return s.Called(i).Get(0).(string)
  988. }
  989. type tCustomLogger struct {
  990. *testing.T
  991. logs []string
  992. errs []string
  993. }
  994. func (tc *tCustomLogger) Logf(format string, args ...interface{}) {
  995. tc.T.Logf(format, args...)
  996. tc.logs = append(tc.logs, fmt.Sprintf(format, args...))
  997. }
  998. func (tc *tCustomLogger) Errorf(format string, args ...interface{}) {
  999. tc.errs = append(tc.errs, fmt.Sprintf(format, args...))
  1000. }
  1001. func (tc *tCustomLogger) FailNow() {}
  1002. func TestLoggingAssertExpectations(t *testing.T) {
  1003. m := new(timer)
  1004. m.On("GetTime", 0).Return("")
  1005. tcl := &tCustomLogger{t, []string{}, []string{}}
  1006. AssertExpectationsForObjects(tcl, m, new(TestExampleImplementation))
  1007. require.Equal(t, 1, len(tcl.errs))
  1008. assert.Regexp(t, regexp.MustCompile("(?s)FAIL: 0 out of 1 expectation\\(s\\) were met.*The code you are testing needs to make 1 more call\\(s\\).*"), tcl.errs[0])
  1009. require.Equal(t, 2, len(tcl.logs))
  1010. assert.Regexp(t, regexp.MustCompile("(?s)FAIL:\tGetTime\\(int\\).*"), tcl.logs[0])
  1011. require.Equal(t, "Expectations didn't match for Mock: *mock.timer", tcl.logs[1])
  1012. }
  1013. func TestAfterTotalWaitTimeWhileExecution(t *testing.T) {
  1014. waitDuration := 1
  1015. total, waitMs := 5, time.Millisecond*time.Duration(waitDuration)
  1016. aTimer := new(timer)
  1017. for i := 0; i < total; i++ {
  1018. aTimer.On("GetTime", i).After(waitMs).Return(fmt.Sprintf("Time%d", i)).Once()
  1019. }
  1020. time.Sleep(waitMs)
  1021. start := time.Now()
  1022. var results []string
  1023. for i := 0; i < total; i++ {
  1024. results = append(results, aTimer.GetTime(i))
  1025. }
  1026. end := time.Now()
  1027. elapsedTime := end.Sub(start)
  1028. assert.True(t, elapsedTime > waitMs, fmt.Sprintf("Total elapsed time:%v should be atleast greater than %v", elapsedTime, waitMs))
  1029. assert.Equal(t, total, len(results))
  1030. for i := range results {
  1031. assert.Equal(t, fmt.Sprintf("Time%d", i), results[i], "Return value of method should be same")
  1032. }
  1033. }
  1034. func TestArgumentMatcherToPrintMismatch(t *testing.T) {
  1035. defer func() {
  1036. if r := recover(); r != nil {
  1037. matchingExp := regexp.MustCompile(
  1038. `\s+mock: Unexpected Method Call\s+-*\s+GetTime\(int\)\s+0: 1\s+The closest call I have is:\s+GetTime\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(int=1\) not matched by func\(int\) bool`)
  1039. assert.Regexp(t, matchingExp, r)
  1040. }
  1041. }()
  1042. m := new(timer)
  1043. m.On("GetTime", MatchedBy(func(i int) bool { return false })).Return("SomeTime").Once()
  1044. res := m.GetTime(1)
  1045. require.Equal(t, "SomeTime", res)
  1046. m.AssertExpectations(t)
  1047. }
  1048. func TestClosestCallMismatchedArgumentInformationShowsTheClosest(t *testing.T) {
  1049. defer func() {
  1050. if r := recover(); r != nil {
  1051. matchingExp := regexp.MustCompile(unexpectedCallRegex(`TheExampleMethod(int,int,int)`, `0: 1\s+1: 1\s+2: 2`, `0: 1\s+1: 1\s+2: 1`, `0: PASS: \(int=1\) == \(int=1\)\s+1: PASS: \(int=1\) == \(int=1\)\s+2: FAIL: \(int=2\) != \(int=1\)`))
  1052. assert.Regexp(t, matchingExp, r)
  1053. }
  1054. }()
  1055. m := new(TestExampleImplementation)
  1056. m.On("TheExampleMethod", 1, 1, 1).Return(1, nil).Once()
  1057. m.On("TheExampleMethod", 2, 2, 2).Return(2, nil).Once()
  1058. m.TheExampleMethod(1, 1, 2)
  1059. }
  1060. func TestClosestCallMismatchedArgumentValueInformation(t *testing.T) {
  1061. defer func() {
  1062. if r := recover(); r != nil {
  1063. matchingExp := regexp.MustCompile(unexpectedCallRegex(`GetTime(int)`, "0: 1", "0: 999", `0: FAIL: \(int=1\) != \(int=999\)`))
  1064. assert.Regexp(t, matchingExp, r)
  1065. }
  1066. }()
  1067. m := new(timer)
  1068. m.On("GetTime", 999).Return("SomeTime").Once()
  1069. _ = m.GetTime(1)
  1070. }
  1071. func unexpectedCallRegex(method, calledArg, expectedArg, diff string) string {
  1072. rMethod := regexp.QuoteMeta(method)
  1073. return fmt.Sprintf(`\s+mock: Unexpected Method Call\s+-*\s+%s\s+%s\s+The closest call I have is:\s+%s\s+%s\s+Diff: %s`,
  1074. rMethod, calledArg, rMethod, expectedArg, diff)
  1075. }
  1076. //go:noinline
  1077. func ConcurrencyTestMethod(m *Mock) {
  1078. m.Called()
  1079. }