From 2fd5b4ef347a26859dc5313e3229371e0dd39019 Mon Sep 17 00:00:00 2001 From: Sven Strittmatter Date: Thu, 2 May 2024 21:43:38 +0200 Subject: [PATCH 1/2] Use More Concise Markdown for Hedlines Signed-off-by: Sven Strittmatter --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 056ba2f..dabc691 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,11 @@ -go-mockdns -============ +# go-mockdns [![Reference](https://godoc.org/github.com/foxcpp/go-mockdns?status.svg)](https://godoc.org/github.com/foxcpp/go-mockdns) Boilerplate for testing of code involving DNS lookups, including ~~unholy~~ hacks to redirect `net.Lookup*` calls. -Example ---------- +## Example Trivial mock resolver, for cases where tested code supports custom resolvers: ```go From 4a6b5bc528c3e8088f3090368cf4884bcf4953bc Mon Sep 17 00:00:00 2001 From: Sven Strittmatter Date: Thu, 2 May 2024 21:56:31 +0200 Subject: [PATCH 2/2] Add More Complete Example How to Setup mocked DNS in Test Signed-off-by: Sven Strittmatter --- README.md | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/README.md b/README.md index dabc691..855b076 100644 --- a/README.md +++ b/README.md @@ -47,3 +47,53 @@ Note, if you need to replace net.Dial calls and tested code supports custom net.Dial, patch the resolver object inside it instead of net.DefaultResolver. If tested code supports Dialer-like objects - use Resolver itself, it implements Dial and DialContext methods. + +### Complete Example for Unit Tests + +Imagine some business code which involves DNS lookups: + +```go +package domain + +import "net" + +func QueryTxtRecord(fqdn string) ([]string, error) { + txtRecords, err := net.LookupTXT(fqdn) + // Do some other stuff here... + return txtRecords, err +} +``` + +Setup mocked DNS in your tests: + +```go +package domain + +import ( + "github.com/foxcpp/go-mockdns" + "github.com/stretchr/testify/assert" + "log" + "net" + "testing" +) + +func TestQueryTxtRecord(t *testing.T) { + srv, err := mockdns.NewServer(map[string]mockdns.Zone{ + "foo.example.com.": { // Dot at the end is mandatory. + TXT: []string{"Hello, world!"}, + }, + }, false) + defer srv.Close() + + if err != nil { + log.Fatalln(err) + } + + srv.PatchNet(net.DefaultResolver) + defer mockdns.UnpatchNet(net.DefaultResolver) + + txtRecords, err = QueryTxtRecord("foo.example.com") + + // Assert here. +} +```