Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing - log and then fail?

I am used to test drive my code. Now that I am new to Go I am trying to get it right as fast as possible. I am using the testing package in the standard library which seem to be good enough. (I also like that it is not yet another external dependency. We are currently at 2 dependencies overall - compared to any Java- or Ruby project.....) Anyways - it looks like an assert in golang looks like this:

func TestSomething(t *testing.T) {
  something := false
  if something {
    t.Log("Oh noes - something is false")
    t.Fail()      
  }
}

I find this verbose and would like to do it on one line instead:

Assert( something, "Oh noes - something is false" )

or something like that. I hope that I have missed something obvious here. What is the best/idiomatic way to do it in go?

UPDATE: just to clarify. If I was to do something like this:

func AssertTrue(t *testing.T, value bool, message string) {
  if value {
    t.Log(message)
    t.Fail()
  }
}

and then write my test like this

func TestSomething(t *testing.T) {
  something := false
  AssertTrue(t, something, "Oh noes - something is false")
}

then it would not be the go way to do it?

like image 492
froderik Avatar asked Sep 05 '13 13:09

froderik


1 Answers

There are external packages that can be integrated with the stock testing framework.

One of them I wrote long ago, gocheck, was intended to sort that kind of use case.

With it, the test case looks like this, for example:

func (s *Suite) TestFoo(c *gocheck.C) {
    // If this succeeds the world is doomed.
    c.Assert("line 1\nline 2", gocheck.Equals, "line 3")
}

You'd run that as usual, with go test, and the failure in that check would be reported as:

----------------------------------------------------------------------
FAIL: foo_test.go:34: Suite.TestFoo

all_test.go:34:
    // If this succeeds the world is doomed.
    c.Assert("line 1\nline 2", gocheck.Equals, "line 3")
... obtained string = "" +
...     "line 1\n" +
...     "line 2"
... expected string = "line 3"

Note how the comment right above the code was included in the reported failure.

There are also a number of other usual features, such as suite and test-specific set up and tear down routines, and so on. Please check out the web page for more details.

It's well maintained as I and other people use it in a number of active projects, so feel free to join on board, or follow up and check out the other similar projects that suit your taste more appropriately.

For examples of gocheck use, please have a look at packages such as mgo, goyaml, goamz, pipe, vclock, juju (massive code base), lpad, gozk, goetveld, tomb, etc. Also gocheck, manages to test itself. It was quite fun to bootstrap that.

like image 177
Gustavo Niemeyer Avatar answered Oct 13 '22 04:10

Gustavo Niemeyer