Hone logo
Hone
Problems

Implementing Table-Driven Tests in Go

Table-driven tests are a powerful and concise way to write tests in Go, promoting readability and maintainability. This challenge asks you to implement a function and then thoroughly test it using table-driven tests, demonstrating your understanding of this testing pattern. This approach helps ensure comprehensive coverage and simplifies adding new test cases.

Problem Description

You are tasked with implementing a function Sum that takes two integers as input and returns their sum. Your primary goal is to write a suite of table-driven tests to verify the correctness of this function across various inputs, including positive numbers, negative numbers, and zero. The tests should cover a range of scenarios to ensure the function behaves as expected under different conditions.

What needs to be achieved:

  1. Implement the Sum function.
  2. Create a test suite using table-driven tests to verify the Sum function.

Key requirements:

  • The Sum function must correctly calculate the sum of two integers.
  • The test suite must include at least five test cases, covering positive, negative, and zero inputs.
  • The test suite must be well-structured and readable, utilizing the table-driven test pattern.
  • Each test case should clearly define the input values and the expected output.

Expected behavior:

The Sum function should return the correct sum of the two input integers. The table-driven tests should pass without any failures, indicating that the function is working as expected.

Edge cases to consider:

  • Large positive and negative numbers (to check for potential overflow, although Go handles this gracefully).
  • Zero as one or both inputs.
  • A mix of positive and negative numbers.

Examples

Example 1:

Input: Sum(2, 3)
Output: 5
Explanation: The sum of 2 and 3 is 5.

Example 2:

Input: Sum(-1, 5)
Output: 4
Explanation: The sum of -1 and 5 is 4.

Example 3:

Input: Sum(0, 0)
Output: 0
Explanation: The sum of 0 and 0 is 0.

Example 4:

Input: Sum(-5, -2)
Output: -7
Explanation: The sum of -5 and -2 is -7.

Example 5:

Input: Sum(1000, -500)
Output: 500
Explanation: The sum of 1000 and -500 is 500.

Constraints

  • The Sum function must accept int type arguments.
  • The test suite must be written in Go.
  • The test suite should be concise and easy to understand.
  • No external libraries are allowed.

Notes

Consider using Go's built-in testing package. The table-driven test pattern involves defining a slice of test cases, where each case contains the input values and the expected output. Iterate through this slice and run the Sum function with the input values, comparing the result with the expected output. Use t.Errorf or t.Fatalf to report test failures. Focus on clarity and readability in your test suite.

Loading editor...
go