Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 52 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -49,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.
}
```