Unit Testing C Code Using Golang's Unit Testing Framework

1,521 views
Skip to first unread message

Shale Craig

unread,
Jan 8, 2014, 2:01:45 PM1/8/14
to golan...@googlegroups.com
For fun, I've written a small library in C, to be used in an embedded C system.

After poking around with a few C unit-test libraries, I decided to test using go's "cgo"+"testing" packages as a way to learn the language.

Though I'm currently blocked on Issue 4030 to have cgo working, it looks like the testing library prevents users from importing the "C" package.

I understand that the testing package is built for golang unit tests, and it's a good practice to prevent users from using C from the tests that are meant to isolate their code, but this prevents me from being able to directly test my C code.

I've written a short .go file (and unit tests for it), but would prefer not to maintain the extra code.

// sample line from the .go file:
// ...
import "C"

func Call_c_foo() int {
 return C.foo()
}

Is there a better/recommended way of doing this?

minux

unread,
Jan 8, 2014, 10:29:32 PM1/8/14
to Shale Craig, golang-nuts
I'm afraid there isn't better alternatives. Essentially you will have two files,
pkg_test.go for tests, and another normal go file that do the cgo interfacing.

However, if you take a look at $GOROOT/msic/cgo/test, you will see that
the trick is this:
// pkg_test.go
package pkg
import "testing"

func TestSomething(t *testing.T) { testSomething(t) }

// pkg.go
import "C"
import "testing"

func testSomething(t *testing.T) {
   // now you can use both C.xxx and t.
}

If organized this way, all it costs is one extra "wrapper" function for each test.
Reply all
Reply to author
Forward
0 new messages