Created
February 9, 2022 22:25
-
-
Save behouba/add87bf4c5104bef854e71781457a9a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package a1 | |
import ( | |
"fmt" | |
"testing" | |
) | |
type Person struct { | |
Name string | |
} | |
type Couple struct { | |
Husband *Person | |
Wife *Person | |
} | |
func (c *Couple) Print() { | |
fmt.Sprintf("%s and %s are a couple", c.Husband.Name, c.Wife.Name) | |
} | |
func CheckCouple(cp *Couple) (output bool) { | |
if cp.Husband != nil && cp.Wife != nil { | |
// safe branch | |
cp.Print() | |
output = true | |
} | |
// nil pointer exception | |
cp.Print() | |
output = false | |
return | |
} | |
type testCase struct { | |
Couple Couple | |
ExpectedOutput bool | |
} | |
// The first set of test cases that miss the defect | |
func TestChecCouple(t *testing.T) { | |
testCases := []testCase{ | |
{ | |
Couple: Couple{ | |
Husband: &Person{Name: "Yves"}, | |
Wife: &Person{Name: "Pety"}, | |
}, | |
ExpectedOutput: true, | |
}, | |
{ | |
Couple: Couple{ | |
Husband: &Person{Name: "Jean didier"}, | |
Wife: &Person{}, | |
}, | |
ExpectedOutput: true, | |
}, | |
} | |
for _, tc := range testCases { | |
if CheckCouple(&tc.Couple) != tc.ExpectedOutput { | |
t.Fail() | |
} | |
} | |
} | |
// The second set of test cases that trigger the defect. | |
func TestChecCouple2(t *testing.T) { | |
testCases := []testCase{ | |
{ | |
Couple: Couple{ | |
Husband: nil, | |
Wife: &Person{Name: "Josi"}, | |
}, | |
ExpectedOutput: false, | |
}, | |
{ | |
Couple: Couple{ | |
Husband: &Person{Name: "Yves"}, | |
Wife: nil, | |
}, | |
ExpectedOutput: false, | |
}, | |
} | |
for _, tc := range testCases { | |
if CheckCouple(&tc.Couple) != tc.ExpectedOutput { | |
t.Fail() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment