testcase is an opinionated behavior-driven-testing library

Table of Contents

Mentioned in Awesome Go GoDoc Build Status Go Report Card codecov

testcase

The testcase package provides tooling to apply BDD testing conventions.

Guide

testcase is a powerful TDD Tooling that requires discipline and understanding about the fundamentals of testing. If you are looking for a guide that helps streamline your knowledge on the topics, then please consider read the below listed articles.

Official API Documentation

If you already use the framework, and you just want pick an example, you can go directly to the API documentation that is kept in godoc format.

Getting Started / Example

Examples kept in godoc format. Every exported functionality aims to have examples provided in the official documentation.

A Basic example:

package main

import (
	"testing"

	"github.com/adamluzsi/testcase"
)

func TestMessageWrapper(t *testing.T) {
	s := testcase.NewSpec(t)
	s.NoSideEffect()

	var (
		message        = testcase.Var{Name: `message`}
		messageWrapper = s.Let(`message wrapper`, func(t *testcase.T) interface{} {
			return MessageWrapper{Message: message.Get(t).(string)}
		})
	)

	s.Describe(`#LookupMessage`, func(s *testcase.Spec) {
		subject := func(t *testcase.T) (string, bool) {
			return messageWrapper.Get(t).(MessageWrapper).LookupMessage()
		}

		s.When(`message is empty`, func(s *testcase.Spec) {
			message.LetValue(s, ``)

			s.Then(`it will return with "ok" as false`, func(t *testcase.T) {
				_, ok := subject(t)
				require.False(t, ok)
			})
		})

		s.When(`message has content`, func(s *testcase.Spec) {
			message.LetValue(s, fixtures.Random.String())

			s.Then(`it will return with "ok" as true`, func(t *testcase.T) {
				_, ok := subject(t)
				require.True(t, ok)
			})

			s.Then(`message received back`, func(t *testcase.T) {
				msg, _ := subject(t)
				require.Equal(t, message.Get(t), msg)
			})
		})
	})
}

Modules

  • httpspec
    • spec module helps you create HTTP API Specs.
  • fixtures
    • fixtures module helps you create random input values for testing

Summary

DRY

testcase provides a way to express common Arrange, Act sections for the Asserts with DRY principle in mind.

  • First you can define your Act section with a method under test as the subject of your test specification
    • The Act section invokes the method under test with the arranged parameters.
  • Then you can build the context of the Act by Arranging the inputs later with humanly explained reasons
    • The Arrange section initializes objects and sets the value of the data that is passed to the method under test.
  • And lastly you can define the test expected outcome in an Assert section.
    • The Assert section verifies that the action of the method under test behaves as expected.

Then adding an additional test edge case to the testing suite becomes easier, as it will have a concrete place where it must be placed.

And if during the creation of the specification, an edge case turns out to be YAGNI, it can be noted, so visually it will be easier to see what edge case is not specified for the given subject.

The value it gives is that to build test for a certain edge case, the required mental model size to express the context becomes smaller, as you only have to focus on one Arrange at a time, until you fully build the bigger picture.

It also implicitly visualize the required mental model of your production code by the nesting. You can read more on that in the nesting section.

Modularization

On top of the DRY convention, any time you need to Arrange a common scenario about your projects domain event, you can modularize these setup blocks in a helper functions.

This helps the readability of the test, while keeping the need of mocks to the minimum as possible for a given test. As a side effect, integration tests can become low hanging fruit for the project.

e.g.:

package mypkg_test

import (
	"testing"

	"my/project/mypkg"


	"github.com/adamluzsi/testcase"

	. "my/project/testing/pkg"
)

func TestMyTypeMyFunc(t *testing.T) {
	s := testcase.NewSpec(t)

	// high level Arrange helpers from my/project/testing/pkg
	SetupSpec(s)
	GivenWeHaveUser(s, `myuser`)
	// .. other givens

	myType := func() *mypkg.MyType { return &mypkg.MyType{} }

	s.Describe(`#MyFunc`, func(s *testcase.Spec) {
		var subject = func(t *testcase.T) { myType().MyFunc(t.I(`myuser`).(*mypkg.User)) } // Act

		s.Then(`edge case description`, func(t *testcase.T) {
			// Assert
			subject(t)
		})
	})
}

Stability

  • The package considered stable.
  • The package use rolling release conventions.
  • No breaking change is planned to the package exported API.
  • The package used for production development.
  • The package API is only extended if the practical use case proves its necessity.

Case Study About testcase Package Origin

Reference Project

Owner
Adam Luzsi
In order to go fast, we need to go well
Adam Luzsi
Similar Resources

Library created for testing JSON against patterns.

Gomatch Library created for testing JSON against patterns. The goal was to be able to validate JSON focusing only on parts essential in given test cas

Oct 28, 2022

A Go library help testing your RESTful API application

RESTit A Go micro-framework to help writing RESTful API integration test Package RESTit provides helps to those who want to write an integration test

Oct 28, 2022

HTTP load testing tool and library. It's over 9000!

HTTP load testing tool and library. It's over 9000!

Vegeta Vegeta is a versatile HTTP load testing tool built out of a need to drill HTTP services with a constant request rate. It can be used both as a

Jan 7, 2023

A WebDriver client and acceptance testing library for Go

A WebDriver client and acceptance testing library for Go

Agouti Agouti is a library for writing browser-based acceptance tests in Google Go. It provides Gomega matchers and plays nicely with Ginkgo or Spec.

Dec 26, 2022

Gostresslib - A golang library for stress testing.

GoStressLib A golang library for stress testing. Install go get github.com/tenhan/gostresslib Usage package main import ( "github.com/tenhan/gostres

Nov 9, 2022

Tesuto - a little library for testing against HTTP services

tesuto import "github.com/guregu/tesuto" tesuto is a little library for testing

Jan 18, 2022

A modern generic testing assertions library for Go

test test is a generics based testing assertions library for Go. There are two packages, test and must. test - assertions that mark the test for failu

Dec 12, 2022

Expressive end-to-end HTTP API testing made easy in Go

baloo Expressive and versatile end-to-end HTTP API testing made easy in Go (golang), built on top of gentleman HTTP client toolkit. Take a look to the

Dec 13, 2022

Simple Go snapshot testing

Simple Go snapshot testing

Incredibly simple Go snapshot testing: cupaloy takes a snapshot of your test output and compares it to a snapshot committed alongside your tests. If t

Jan 5, 2023
Comments
  • # randomized test order

    # randomized test order

    The goal of this feature to avoid implicit test ordering in the testing suite.

    A testing suite is also something that evolves with a project. New tests will be added, old tests will be deleted, and some will be updated to express changes in the business rules. To avoid problems as our test suites grow and change, it’s important to keep test cases independent.

    Test execution should be randomised, but the random order should be recreatable. The reason for this because developers can observe test randomly failing, and then using the test execution order seed, they can hunt down the test ordering based tests by using the same testing order random seed.

  • support parameter passing with testcase.T#Defer

    support parameter passing with testcase.T#Defer

    What would it do

    This would allow to pass values from a scope with pass by value idiom.

    What is the Issue

    when Let memorize a pointer type and during the let block, it declares a T#Defer, the function body is only evaluated eventually. So if the struct content is mutated during the test, and then the deferred function tries to be executed with a value that might not be available at that point, it could cause issues.

    Example

    t.Defer(func(value string) {  }, `hello, world`)
    
A yaml data-driven testing format together with golang testing library

Specimen Yaml-based data-driven testing Specimen is a yaml data format for data-driven testing. This enforces separation between feature being tested

Nov 24, 2022
The test suite to demonstrate the chaos experiment behavior in different scenarios

Litmus-E2E The goal of litmus e2e is to provide the test suite to demonstrate the chaos experiment behavior in different scenarios. As the name sugges

Jul 7, 2022
Markdown based document-driven RESTful API testing.
Markdown based document-driven RESTful API testing.

silk Markdown based document-driven web API testing. Write nice looking Markdown documentation (like this), and then run it using the silk command Sim

Dec 18, 2022
siusiu (suite-suite harmonics) a suite used to manage the suite, designed to free penetration testing engineers from learning and using various security tools, reducing the time and effort spent by penetration testing engineers on installing tools, remembering how to use tools.
siusiu (suite-suite harmonics) a suite used to manage the suite, designed to free penetration testing engineers from learning and using various security tools, reducing the time and effort spent by penetration testing engineers on installing tools, remembering how to use tools.

siusiu (suite-suite harmonics) a suite used to manage the suite, designed to free penetration testing engineers from learning and using various security tools, reducing the time and effort spent by penetration testing engineers on installing tools, remembering how to use tools.

Dec 12, 2022
Learn Go with test-driven development
Learn Go with test-driven development

Learn Go with Tests Art by Denise Formats Gitbook EPUB or PDF Translations 中文 Português 日本語 한국어 Support me I am proud to offer this resource for free,

Jan 1, 2023
Simple test driven approach in "GOLANG"
Simple test driven approach in

Testing in GOLANG Usage Only test go test -v Coverage go test -cover or go test -coverprofile=coverage.out go tool cover -html=coverage.out Benchmark

Dec 5, 2021
Behaviour Driven Development tests generator for Golang
Behaviour Driven Development tests generator for Golang

gherkingen It's a Behaviour Driven Development (BDD) tests generator for Golang. It accept a *.feature Cucumber/Gherkin file and generates a test boil

Dec 16, 2022
This repository includes consumer driven contract test for provider, unit test and counter api.

This repository includes consumer driven contract test for provider, unit test and counter api.

Feb 1, 2022
Fortio load testing library, command line tool, advanced echo server and web UI in go (golang). Allows to specify a set query-per-second load and record latency histograms and other useful stats.
Fortio load testing library, command line tool, advanced echo server and web UI in go (golang). Allows to specify a set query-per-second load and record latency histograms and other useful stats.

Fortio Fortio (Φορτίο) started as, and is, Istio's load testing tool and now graduated to be its own project. Fortio is also used by, among others, Me

Jan 2, 2023
:exclamation:Basic Assertion Library used along side native go testing, with building blocks for custom assertions

Package assert Package assert is a Basic Assertion library used along side native go testing Installation Use go get. go get github.com/go-playground/

Jan 6, 2023