Skip to content

Instantly share code, notes, and snippets.

@amityt
Created March 16, 2023 11:39
Show Gist options
  • Save amityt/0966852230c0dc4d6d531ccc3bffe692 to your computer and use it in GitHub Desktop.
Save amityt/0966852230c0dc4d6d531ccc3bffe692 to your computer and use it in GitHub Desktop.
Go interfaces and test cases
package main
import "testing"
type calculateTest struct {
arg1, arg2, expectedResult int
}
var addTests = []calculateTest{
{2, 3, 5},
{4, 8, 12},
{6, 9, 14},
{3, 10, 13},
}
var subtractTests = []calculateTest{
{2, 3, -1},
{4, 8, -4},
{9, 6, 3},
{13, 10, 3},
}
func TestAdd(t *testing.T) {
for _, test := range addTests {
var calculate Calculate
calculate = &InputNumbers{
FirstNumber: test.arg1,
SecondNumber: test.arg2,
}
result := calculate.Add()
if result != test.expectedResult {
t.Errorf("Output %d not equal to expected %d", result, test.expectedResult)
}
}
}
func TestSubtract(t *testing.T) {
for _, test := range subtractTests {
var calculate Calculate
calculate = &InputNumbers{
FirstNumber: test.arg1,
SecondNumber: test.arg2,
}
result := calculate.Subtract()
if result != test.expectedResult {
t.Errorf("Output %d not equal to expected %d", result, test.expectedResult)
}
}
}
package main
import (
"fmt"
)
type Calculate interface {
Add() int
Subtract() int
Multiply() int
}
type InputNumbers struct {
FirstNumber int
SecondNumber int
}
func (i *InputNumbers) Add() int {
return i.FirstNumber + i.SecondNumber
}
func (i *InputNumbers) Subtract() int {
return i.FirstNumber - i.SecondNumber
}
func (i *InputNumbers) Multiply() int {
return i.FirstNumber * i.SecondNumber
}
func main() {
var result Calculate
result = &InputNumbers{
FirstNumber: 10,
SecondNumber: 5,
}
add := result.Add()
subtract := result.Subtract()
multiply := result.Multiply()
fmt.Printf("Result for the Calculate operations is Add: %d, Subtract: %d, Multiply: %d", add, subtract, multiply)
}
@amityt
Copy link
Author

amityt commented Mar 16, 2023

The result of test cases are:
=== RUN TestAdd
add_test.go:34: Output 15 not equal to expected 14
--- FAIL: TestAdd (0.00s)
=== RUN TestSubtract
--- PASS: TestSubtract (0.00s)
FAIL
exit status 1
FAIL _/Users/amit.das/Desktop/test-cases 1.619s

The test TestAdd has failed since one of the results is incorrect.
Test TestSubtract has passed since all the test cases are valid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment