Reputation: 1950
I am implementing a storer that is backed by leveldb (https://github.com/syndtr/goleveldb) in go. I am new to go and am trying to figure out how I get test coverage for the condition in the code below where perr != nil. I can test my own errors ok, but I can't figure out how to reliably get the Put method of leveldb to return an error. Mocking out a db just to get test coverage up for a few edge cases seems like a lot of work for not much reward. Is mocking leveldb my only real choice here? If so what's the recommended mocking framework for go? If there's another way what is it?
if err == leveldb.ErrNotFound {
store.Lock()
perr := store.ldb.Put(itob(p.ID), p.ToBytes(), nil)
if perr != nil {
store.Unlock()
return &StorerError{
Message: fmt.Sprintf("leveldb put error could not create puppy %d : %s", p.ID, perr),
Code: 501,
}
}
store.Unlock()
return nil
}
Upvotes: 2
Views: 892
Reputation: 1324757
Mocking is the general chosen approach for this kind of test, which is why golang/mock
, for instance, has a mockgen
command, to generate the test code.
mockgen
has two modes of operation: source and reflect.
- Source mode generates mock interfaces from a source file.
It is enabled by using the-source
flag.
Other flags that may be useful in this mode are-imports
and-aux_files
.Example:
mockgen -source=foo.go [other options]
- Reflect mode generates mock interfaces by building a program that uses reflection to understand interfaces.
It is enabled by passing two non-flag arguments: an import path, and a comma-separated list of symbols.Example:
mockgen database/sql/driver Conn,Driver
Upvotes: 3