Joseph Jude

Consult . Code . Coach

Testing Beego Applications

code . golang . testing . beego

I have been learning Go for few days. I like the language so far. The language is compact which makes it easy to understand and remember.

I develop primarily for the web. In Python and Nodejs world, there are fantastic web-frameworks like Flask, Django and Sailsjs. My search for such a web-framework in Go lead to Beego. It resembles Django in many ways—it comes with all batteries included.

In this post, I describe how to test a Beego app using the built-in testing module[1]. For testing, Beego completely relies on Go testing module.

I started with this template as proposed in the reddit comment:

func TestMain(m *testing.M) {
    // your functions

    retCode := m.Run()

    // your functions

    // call with result of m.Run()

Trouble with this template is that go test will test only TestMain. As you write other TestXXX functions, you should remember to include them within TestMain, which defeats the purpose of automation. So I came up with this template:

func init() {
  //this is setup function
  //this will be invoked automatically

func TestXXX1(t *testing.T) {

func TestXXX2(t *testing.T) {

func TestTeardown(t *testing.T) {
    //check if teardown was successful

func tearDown() {

In this way, when more TestXXX functions are added, they will be automatically invoked by go test command.

If you want to use a different databse for testing purposes, you can create it in init()

func init() {
    _, file, _, _ := runtime.Caller(1)
    apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator))))

    orm.RegisterDriver("sqlite", orm.DR_Sqlite)
    orm.RegisterDataBase("default", "sqlite3", "my_test.db")

    name := "default"
    force := false
    verbose := false
    err := orm.RunSyncdb(name, force, verbose)
    if err != nil {


Equivalent tearDown() will be:

func tearDown() {
    beego.Debug("Starting teardown")
    _, file, _, _ := runtime.Caller(1)
    apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator))))
    db := apppath + string(filepath.Separator) + "my_test.db"

Now go enjoy your testing.

  1. As of 1.4, Go supports setup() and teardown() for tests.

Like the post? Retweet it. Got comments? Reply.

Testing Beego Applications by @jjude:

— Joseph Jude (@jjude) December 15, 2016
Share this on: Twitter / /


comments powered by Disqus