oglemock

package
v0.0.0-...-0c3e7f9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 17, 2015 License: MIT, Apache-2.0 Imports: 7 Imported by: 0

README

oglemock is a mocking framework for the Go programming language with the following features:

  • An extensive and extensible set of matchers for expressing call expectations (provided by the oglematchers package).

  • Clean, readable output that tells you exactly what you need to know.

  • Style and semantics similar to Google Mock and Google JS Test.

  • Seamless integration with the ogletest unit testing framework.

It can be integrated into any testing framework (including Go's testing package), but out of the box support is built in to ogletest and that is the easiest place to use it.

Installation

First, make sure you have installed Go 1.0.2 or newer. See here for instructions.

Use the following command to install oglemock and its dependencies, and to keep them up to date:

go get -u github.com/smartystreets/assertions/internal/oglemock
go get -u github.com/smartystreets/assertions/internal/oglemock/createmock

Those commands will install the oglemock package itself, along with the createmock tool that is used to auto-generate mock types.

Generating and using mock types

Automatically generating a mock implementation of an interface is easy. If you want to mock interfaces Bar and Baz from package foo, simply run the following:

createmock foo Bar Baz

That will print source code that can be saved to a file and used in your tests. For example, to create a mock_io package containing mock implementations of io.Reader and io.Writer:

mkdir mock_io
createmock io Reader Writer > mock_io/mock_io.go

The new package will be named mock_io, and contain types called MockReader and MockWriter, which implement io.Reader and io.Writer respectively.

For each generated mock type, there is a corresponding function for creating an instance of that type given a Controller object (see below). For example, to create a mock reader:

someController := [...]  // See next section.
someReader := mock_io.NewMockReader(someController, "Mock file reader")

The snippet above creates a mock io.Reader that reports failures to someController. The reader can subsequently have expectations set up and be passed to your code under test that uses an io.Reader.

Getting ahold of a controller

oglemock.Controller is used to create mock objects, and to set up and verify expectations for them. You can create one by calling NewController with an ErrorReporter, which is the basic type used to interface between oglemock and the testing framework within which it is being used.

If you are using ogletest you don't need to worry about any of this, since the TestInfo struct provided to your test's SetUp function already contains a working Controller that you can use to create mock object, and you can use the built-in ExpectCall function for setting expectations. (See the ogletest documentation for more info.) Otherwise, you will need to implement the simple ErrorReporter interface for your test environment.

Documentation

For thorough documentation, including information on how to set up expectations, see here.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Action

type Action interface {
	// Set the signature of the function with which this action is being used.
	// This must be called before Invoke is called.
	SetSignature(signature reflect.Type) error

	// Invoke runs the specified action, given the arguments to the mock method.
	// It returns zero or more values that may be treated as the return values of
	// the method. If the action doesn't return any values, it may return the nil
	// slice.
	//
	// You must call SetSignature before calling Invoke.
	Invoke(methodArgs []interface{}) []interface{}
}

Action represents an action to be taken in response to a call to a mock method.

func Invoke

func Invoke(f interface{}) Action

Create an Action that invokes the supplied function, returning whatever it returns. The signature of the function must match that of the mocked method exactly.

func Return

func Return(vals ...interface{}) Action

Return creates an Action that returns the values passed to Return as arguments, after suitable legal type conversions. The following rules apply. Given an argument x to Return and a corresponding type T in the method's signature, at least one of the following must hold:

  • x is assignable to T. (See "Assignability" in the language spec.) Note that this in particular applies that x may be a type that implements an interface T. It also implies that the nil literal can be used if T is a pointer, function, interface, slice, channel, or map type.

  • T is any numeric type, and x is an int that is in-range for that type. This facilities using raw integer constants: Return(17).

  • T is a floating-point or complex number type, and x is a float64. This facilities using raw floating-point constants: Return(17.5).

  • T is a complex number type, and x is a complex128. This facilities using raw complex constants: Return(17+2i).

type Controller

type Controller interface {
	// ExpectCall expresses an expectation that the method of the given name
	// should be called on the supplied mock object. It returns a function that
	// should be called with the expected arguments, matchers for the arguments,
	// or a mix of both.
	//
	// fileName and lineNumber should indicate the line on which the expectation
	// was made, if known.
	//
	// For example:
	//
	//     mockWriter := [...]
	//     controller.ExpectCall(mockWriter, "Write", "foo.go", 17)(ElementsAre(0x1))
	//         .WillOnce(Return(1, nil))
	//
	// If the mock object doesn't have a method of the supplied name, the
	// function reports a fatal error and returns nil.
	ExpectCall(
		o MockObject,
		methodName string,
		fileName string,
		lineNumber int) PartialExpecation

	// Finish causes the controller to check for any unsatisfied expectations,
	// and report them as errors if they exist.
	//
	// The controller may panic if any of its methods (including this one) are
	// called after Finish is called.
	Finish()

	// HandleMethodCall looks for a registered expectation matching the call of
	// the given method on mock object o, invokes the appropriate action (if
	// any), and returns the values returned by that action (if any).
	//
	// If the action returns nothing, the controller returns zero values. If
	// there is no matching expectation, the controller reports an error and
	// returns zero values.
	//
	// If the mock object doesn't have a method of the supplied name, the
	// arguments are of the wrong type, or the action returns the wrong types,
	// the function reports a fatal error.
	//
	// HandleMethodCall is exported for the sake of mock implementations, and
	// should not be used directly.
	HandleMethodCall(
		o MockObject,
		methodName string,
		fileName string,
		lineNumber int,
		args []interface{}) []interface{}
}

Controller represents an object that implements the central logic of oglemock: recording and verifying expectations, responding to mock method calls, and so on.

func NewController

func NewController(reporter ErrorReporter) Controller

NewController sets up a fresh controller, without any expectations set, and configures the controller to use the supplied error reporter.

type ErrorReporter

type ErrorReporter interface {
	// Report that some failure (e.g. an unsatisfied expectation) occurred. If
	// known, fileName and lineNumber should contain information about where it
	// occurred. The test may continue if the test framework supports it.
	ReportError(fileName string, lineNumber int, err error)

	// Like ReportError, but the test should be halted immediately. It is assumed
	// that this method does not return.
	ReportFatalError(fileName string, lineNumber int, err error)
}

ErrorReporter is an interface that wraps methods for reporting errors that should cause test failures.

type Expectation

type Expectation interface {
	// Times expresses that a matching method call should happen exactly N times.
	// Times must not be called more than once, and must not be called after
	// WillOnce or WillRepeatedly.
	//
	// The full rules for the cardinality of an expectation are as follows:
	//
	//  1. If an explicit cardinality is set with Times(N), then anything other
	//     than exactly N matching calls will cause a test failure.
	//
	//  2. Otherwise, if there are any one-time actions set up, then it is
	//     expected there will be at least that many matching calls. If there is
	//     not also a fallback action, then it is expected that there will be
	//     exactly that many.
	//
	//  3. Otherwise, if there is a fallback action configured, any number of
	//     matching calls (including zero) is allowed.
	//
	//  4. Otherwise, the implicit cardinality is one.
	//
	Times(n uint) Expectation

	// WillOnce configures a "one-time action". WillOnce can be called zero or
	// more times, but must be called after any call to Times and before any call
	// to WillRepeatedly.
	//
	// When matching method calls are made on the mock object, one-time actions
	// are invoked one per matching call in the order that they were set up until
	// they are exhausted. Afterward the fallback action, if any, will be used.
	WillOnce(a Action) Expectation

	// WillRepeatedly configures a "fallback action". WillRepeatedly can be
	// called zero or one times, and must not be called before Times or WillOnce.
	//
	// Once all one-time actions are exhausted (see above), the fallback action
	// will be invoked for any further method calls. If WillRepeatedly is not
	// called, the fallback action is implicitly an action that returns zero
	// values for the method's return values.
	WillRepeatedly(a Action) Expectation
}

Expectation is an expectation for zero or more calls to a mock method with particular arguments or sets of arguments.

type InternalExpectation

type InternalExpectation struct {

	// Matchers that the arguments to the mock method must satisfy in order to
	// match this expectation.
	ArgMatchers []oglematchers.Matcher

	// The name of the file in which this expectation was expressed.
	FileName string

	// The line number at which this expectation was expressed.
	LineNumber int

	// The number of times this expectation should be matched, as explicitly
	// listed by the user. If there was no explicit number expressed, this is -1.
	ExpectedNumMatches int

	// Actions to be taken for the first N calls, one per call in order, where N
	// is the length of this slice.
	OneTimeActions []Action

	// An action to be taken when the one-time actions have expired, or nil if
	// there is no such action.
	FallbackAction Action

	// The number of times this expectation has been matched so far.
	NumMatches uint
	// contains filtered or unexported fields
}

InternalExpectation is exported for purposes of testing only. You should not touch it.

InternalExpectation represents an expectation for zero or more calls to a mock method, and a set of actions to be taken when those calls are received.

func InternalNewExpectation

func InternalNewExpectation(
	reporter ErrorReporter,
	methodSignature reflect.Type,
	args []interface{},
	fileName string,
	lineNumber int) *InternalExpectation

InternalNewExpectation is exported for purposes of testing only. You should not touch it.

func (*InternalExpectation) Times

func (e *InternalExpectation) Times(n uint) Expectation

func (*InternalExpectation) WillOnce

func (e *InternalExpectation) WillOnce(a Action) Expectation

func (*InternalExpectation) WillRepeatedly

func (e *InternalExpectation) WillRepeatedly(a Action) Expectation

type MockObject

type MockObject interface {
	// Oglemock_Id returns an identifier for the mock object that is guaranteed
	// to be unique within the process at least until the mock object is garbage
	// collected.
	Oglemock_Id() uintptr

	// Oglemock_Description returns a description of the mock object that may be
	// helpful in test failure messages.
	Oglemock_Description() string
}

MockObject is an interface that mock object implementations must conform to in order to register expectations with and hand off calls to a MockController. Users should not interact with this interface directly.

type PartialExpecation

type PartialExpecation func(...interface{}) Expectation

PartialExpecation is a function that should be called exactly once with expected arguments or matchers in order to set up an expected method call. See Controller.ExpectMethodCall below. It returns an expectation that can be further modified (e.g. by calling WillOnce).

If the arguments are of the wrong type, the function reports a fatal error and returns nil.

Directories

Path Synopsis
createmock is used to generate source code for mock versions of interfaces from installed packages.
createmock is used to generate source code for mock versions of interfaces from installed packages.
Package generate implements code generation for mock classes.
Package generate implements code generation for mock classes.
test_cases/complicated_pkg
Package complicated_pkg contains an interface with lots of interesting cases, for use in integration testing.
Package complicated_pkg contains an interface with lots of interesting cases, for use in integration testing.
test_cases/renamed_pkg
A package that calls itself something different than its package path would have you believe.
A package that calls itself something different than its package path would have you believe.
sample

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL