apitest

API overview

Every exported type and method in apitest, grouped by where it is used.

This page lists the whole API of github.com/steinfletcher/apitest v1.8.0, the release these docs are tested against, with links to the guides. Signatures and doc comments are on pkg.go.dev.

Starting a test

FunctionReturnsDescription
New(name ...string)*APITestStarts a test. The optional name appears in reports.
Handler(h http.Handler)*APITestShorthand for New().Handler(h).
HandlerFunc(f http.HandlerFunc)*APITestShorthand for New().HandlerFunc(f).

APITest

Configuration methods return *APITest. The request methods return *Request. See anatomy of a test.

MethodDescription
Handler(http.Handler), HandlerFunc(http.HandlerFunc)The handler under test. Requests
Mocks(...*Mock)The mocks for this test. Replaces earlier mocks. Mocks
HttpClient(*http.Client)Mock the transport of this client instead of http.DefaultTransport. HTTP clients
EnableMockResponseDelay()Honour FixedDelay on mocks. Failures and latency
ObserveMocks(Observe)Called for every mocked call. Observing mocks
Observe(...Observe)Called with the final response. Replaces earlier observers. Debugging
Debug()Print every request and response. Debugging
Report(ReportFormatter)Render the test as a report. Sequence diagrams
Recorder(*Recorder)Use this recorder, for custom events. Custom reports
Meta(map[string]any)Values passed to reports. Sequence diagrams
Intercept(Intercept)Change the request before it is sent. Intercept
EnableNetworking(...*http.Client)Send the request over the network. End-to-end tests
Verifier(Verifier)Replace the assertion implementation. Test frameworks
UseFS(fs.FS)The file system for MultipartFile. Forms
Host(string)The request Host. Defaults to sut. Requests
Get, Post, Put, Patch, Delete (url string)Start the request with a method and URL.
Getf, Postf, Putf, Patchf, Deletef (format string, args ...any)As above, with a formatted URL.
Method(string)Start the request with a method. Set the URL with URL.
HttpRequest(*http.Request)Use a ready-made request. Requests
Request(), Response()The request and expectation builders of the test.
RecorderHook(RecorderHook)Deprecated. Use Recorder.

Request

Request methods return *Request. Expect(t) returns *Response.

MethodDescription
URL(string), URLf(format, args...)The URL.
Header(key, value), Headers(map[string]string)Add headers. Headers
ContentType(string)Set Content-Type.
Query(key, value), QueryParams(map[string]string), QueryCollection(map[string][]string)Add query parameters. Query parameters
Cookie(name, value), Cookies(...*Cookie)Add cookies. Cookies
Body(string), Bodyf(format, args...), BodyFromFile(path)Set the body. Body
JSON(any), JSONFromFile(path)Set a JSON body and content type. Body
FormData(name, values...)Add URL encoded form fields. Forms
MultipartFormData(name, values...), MultipartFile(name, paths...)Add multipart fields and files. Forms
GraphQLQuery(query, variables...), GraphQLRequest(GraphQLRequestBody)Build a GraphQL request. GraphQL
BasicAuth(username, password)Set basic auth credentials. Authentication
WithContext(context.Context)Set the request context. Context
Expect(TestingT)End the request and start the expectations.

Response

Expectation methods return *Response. End() returns Result.

MethodDescription
Status(int)The status code. Assertions
Body(string), Bodyf(format, args...), BodyFromFile(path)The body, compared as JSON when valid JSON. Body
Header(key, value), Headers(map[string]string)Header values. Headers
HeaderPresent(key), HeaderNotPresent(key)Header presence.
Cookie(name, value), Cookies(...*Cookie)Cookies. Cookies
CookiePresent(name), CookieNotPresent(name)Cookie presence.
Assert(func(*http.Response, *http.Request) error)A custom assertion. Custom assertions
End()Run the test.

Result

MemberDescription
Response *http.ResponseA copy of the final response. The result
JSON(any)Decode the response body.
UnmatchedMocks() []UnmatchedMockMocks no request matched. Each has a URL url.URL.

Mock

NewMock() returns *Mock. The verb methods return *MockRequest.

MethodDescription
Get, Post, Put, Patch, Delete, Head (url string)Match the method and URL. Defining mocks
Getf, Postf, Putf, Patchf, Deletef (format, args...)As above, with a formatted URL.
Method(string)Match any method. Matches any URL unless URL or URLf sets one. Request matchers
HttpClient(*http.Client), Debug()Options for standalone mocks.
Matches(*http.Request) []errorRun the mock's matchers against a request.

MockRequest

Matchers return *MockRequest. RespondWith() returns *MockResponse. See request matchers.

MethodMatches
URL(url), URLf(format, args...)The URL, for a mock started with Method. Added in v1.7.0.
Header(key, pattern), Headers(map[string]string)Header values, as regular expressions.
HeaderPresent(key), HeaderNotPresent(key)Header presence.
Query(key, pattern), QueryParams(map[string]string), QueryCollection(map[string][]string)Query values, as regular expressions.
QueryPresent(key), QueryNotPresent(key)Query presence.
Body(string), Bodyf(format, args...), BodyFromFile(path), JSON(any)The body, exactly or as equivalent JSON.
BodyRegexp(pattern)The body, as a regular expression.
FormData(key, patterns...)Form values, as regular expressions.
FormDataPresent(key), FormDataNotPresent(key)Form field presence.
Cookie(name, value), CookiePresent(name), CookieNotPresent(name)Cookies.
BasicAuth(username, password)Basic auth credentials.
AddMatcher(Matcher)A custom matcher.
RespondWith()End the request and start the response.

MockResponse

Methods return *MockResponse. End() returns *Mock. See responses.

MethodDescription
Status(int)The status code. Defaults to 0.
Header(key, value), Headers(map[string]string)Response headers.
Cookie(name, value), Cookies(...*Cookie)Response cookies.
Body(string), Bodyf(format, args...), BodyFromFile(path), JSON(any)The body.
Times(int), AnyTimes()How many calls the mock answers. Call counts
Timeout(), FixedDelay(ms int64)Fail with a timeout, or respond slowly. Failures and latency
End()Finish the mock.
EndStandalone(...*Mock) func()Install as a standalone mock and return the reset function.

StandaloneMocks

NewStandaloneMocks returns a *StandaloneMocks. See standalone mocks.

Function or methodDescription
NewStandaloneMocks(...*Mock)Group mocks for standalone use.
HttpClient(*http.Client), Debug()Options.
End() func()Install the mocks and return the reset function.
Function or methodDescription
NewCookie(name)Start a cookie.
Value, Path, Domain, Expires, MaxAge, Secure, HttpOnlySet a field. Unset fields are ignored in comparisons.
FromHTTPCookie(*http.Cookie), ToHttpCookie()Convert to and from *http.Cookie.

Reports

NameDescription
SequenceDiagram(path ...string)Returns a *SequenceDiagramFormatter, the HTML sequence diagram formatter. Its Format method writes the report.
ReportFormatterThe interface for custom formatters.
NewTestRecorder(), RecorderThe recorded title, subtitle, meta data and events.
Recorder.AddHttpRequest, AddHttpResponse, AddMessageRequest, AddMessageResponseAdd events.
Recorder.AddTitle, AddSubTitle, AddMeta, Reset, ResponseStatusManage the recorder.
HttpRequest, HttpResponse, MessageRequest, MessageResponseThe event types. Each implements Event, whose GetTime returns when it happened.
ConsumerDefaultName, SystemUnderTestDefaultNameThe participant names cli and sut.

Types for extension

TypeSignature
Assertfunc(*http.Response, *http.Request) error
Matcherfunc(*http.Request, *MockRequest) error
Observefunc(*http.Response, *http.Request, *APITest)
Interceptfunc(*http.Request)
TestingTErrorf, Fatal and Fatalf. Test frameworks
VerifierEqual, True, JSONEq, Fail and NoError. Implemented by DefaultVerifier and NoopVerifier.
GraphQLRequestBodyQuery, Variables and OperationName.

Ready-made assertions

IsSuccess, IsClientError and IsServerError assert that the status code is in the 200 to 399, 400 to 499, or 500 and above range.

Internal and deprecated

These are exported but rarely needed in tests.

NameDescription
TransportThe http.RoundTripper that answers mocked calls. Hijack installs it, Reset restores the original transport, and RoundTrip matches a request against the mocks. apitest manages it for you.
OSFSThe default fs.FS behind UseFS. Open reads from the operating system.
InboundRequest, FinalResponseDeprecated. Not used by apitest, and kept for compatibility.
RecorderHookDeprecated. Use Recorder.

Sub-packages

PackageContents
github.com/steinfletcher/apitest/x/dbWrapWithRecorder and WrapConnectorWithRecorder. Database interactions
github.com/steinfletcher/apitest/mocksMockVerifier, a stubbable Verifier.

On this page