2

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
    }
1
  • 1
    "Mocking out a db just to get test coverage up for a few edge cases seems like a lot of work" -- isn't that the entire reason mocks exist? Besides, you don't need to mock the entire db--just the parts your function depends on. Commented Jul 6, 2019 at 7:53

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.