Intro
Testify: A toolkit with common assertions and mocks that plays nicely with the standard library
Official website link
Assert Example
The testing target function Add:
1 | package main |
Table-structured testing using assert like below:
1 | package main |
Run the test command and it will show rich and structured testing results
1 | Go test |
Suite example
The testify suite in Go is used to organize and structure your tests in a more modular and reusable way.
Test Suite Structure: By using suite.Suite from testify, all test cases for the Calculator are grouped into a single CalculatorTestSuite. This allows for a clear separation of tests related to the Calculator while promoting reusability and consistency across multiple tests.
Setup and Teardown: The SetupTest and TearDownTest methods allow for reusable setup and cleanup logic, avoiding repetitive code in individual test cases. This makes the test suite more maintainable and modular.
Modularity with Testify: Using assert from testify provides reusable and concise assertions. This avoids the need for verbose error handling and enhances test readability.
Code block obtained from LINK
1 | package main |
Mock Example
Mock Service Behavior: The line mockSvc.On("GetData", "123").Return("mocked data", nil) mocks the behavior of GetData("123"), returning "mocked data" with no error.
Test ProcessData: The test checks whether calling ProcessData(mockSvc, "123") returns the expected output: Expected output: "Processed: mocked data".
Assertions:
assert.NoError verifies there are no errors. assert.Equal checks if the result equals "Processed: mocked data".
Verify Mock Expectations: mockSvc.AssertExpectations(t) ensures the mock behavior (calling GetData with the argument "123") matches the defined expectations.
1 | package main |
When
When to Use suite:
* Multiple Test Cases: Use suite when you have several related test cases that require similar setup, teardown, or shared dependencies.
* Shared Setup/Teardown: When you need to initialize resources (e.g., database, external services, mock objects) before running the tests and clean them up after.
* Complex Testing Scenarios: Use suite when you have more complex tests that involve multiple test cases interacting with mock objects or other dependencies in different ways.
* Organizing Test Cases: When you want to logically group your tests, improve test readability, and reduce repetition by centralizing common setup.
When to Use mock:
* Isolated Unit Tests: Use mock when you want to mock out individual dependencies in a specific test. For example, when you want to mock an external service, database, or API.
Simulating Return Values and Errors: When you need to return specific values or errors from a method that you don’t want to actually execute during the test.
* Simple Tests: When you don’t need extensive setup/teardown and just want to mock a method for one or two test cases.