Skip to content

Instantly share code, notes, and snippets.

@AntonStoeckl
Last active January 14, 2022 20:26
Show Gist options
  • Save AntonStoeckl/d97e5d07b6312eca0ea98684150c750b to your computer and use it in GitHub Desktop.
Save AntonStoeckl/d97e5d07b6312eca0ea98684150c750b to your computer and use it in GitHub Desktop.
Example for blog post Go bits: Interfaces and Nil Pointers
package commandhandling_test
import (
"testing"
"github.com/matryer/is"
"go-bits/interfaces-and-nil/commandhandling"
)
func TestHandlingTypedNilInterface(t *testing.T) {
// Arrange
shouldBe := is.New(t)
handler := commandhandling.NewCommandHandler()
var nilInterface commandhandling.Command
// Act
err := handler.Handle(nilInterface)
// Assert
shouldBe.True(err != nil)
shouldBe.True(err == commandhandling.ErrCommandIsNilInterface)
}
func TestHandlingUntypedNil(t *testing.T) {
// Arrange
shouldBe := is.New(t)
handler := commandhandling.NewCommandHandler()
// Act
err := handler.Handle(nil)
// Assert
shouldBe.True(err != nil)
shouldBe.True(err == commandhandling.ErrCommandIsNilInterface)
}
func TestHandlingNilPointerCommand(t *testing.T) {
// Arrange
shouldBe := is.New(t)
handler := commandhandling.NewCommandHandler()
var nilCommand *commandhandling.RegisterCustomer
// Act
err := handler.Handle(nilCommand)
// Assert
shouldBe.True(err != nil)
shouldBe.True(err == commandhandling.ErrCommandIsNilPointer)
}
func TestHandlingInterfaceWithUnderlyingNilPointer(t *testing.T) {
// Arrange
shouldBe := is.New(t)
handler := commandhandling.NewCommandHandler()
var nilCommand *commandhandling.RegisterCustomer
var interfaceWithUnderlyingNilPointer commandhandling.Command = nilCommand
// Act
err := handler.Handle(interfaceWithUnderlyingNilPointer)
// Assert
shouldBe.True(err != nil)
shouldBe.True(err == commandhandling.ErrCommandIsNilPointer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment