DEV Community

loading...

Discussion on: Building a finance tracking REST API using Go with TDD - Part 1

Collapse
gaumala profile image
Gabriel Aumala

Minor observation: GOPATH is usually just ~/go and it contains more than src.

I tried to do something like this once, but Go's built-in test framework isn't really designed for this sort of thing. When running integration tests with the database you usually want to clean the database on setup/teardown, but Go runs each test file in parallel so there's the chance that you wipe the database in one file while other tests are running. It's not feasible to have all your tests in a single file, so I just abandoned the idea. I'm curious if you have find a workaround for this.

Also, if most of your work is done by a database (like the vast majority of REST APIs), then the best things about Go (concurrency & performance) can't really help you. I personally believe that Go isn't really a good choice for REST APIs. There are probably simpler alternatives. However it's probably a good exercise to write a small API in Go if your sole objective is to learn more about HTTP since it's very low level compared to more popular languages.

Collapse
alirezabashiri profile image
Alireza Bashiri Author

Good catch! $GOPATH I mean. That's obviously a mistake. About the test cases in a single file I have no problem with it, for example; if you look at Django testing that's how they're doing it. I believe in one simple package and many test files and I always do it.

Here's a simple example;

budgets.go
budgets_test.go
categories.go
categories_test.go
transactions.go
transactions_test.go

Also as I'm going to show, with github.com/go-pg/orm.CreateTableOptions which has a specific field called Temp we're going to create a temporary database for each test case and do the isolation.

func TestMain(m *testing.M) {
    testServer = newServer(
        pg.Connect(&pg.Options{
            User:     "alireza",
            Password: "alireza",
            Database: "alireza_test",
        }),
        mux.NewRouter(),
    )

    testServer.db.CreateTable(&budget{}, &orm.CreateTableOptions{
        Temp: true,
    })

    os.Exit(m.Run())
}

I've more than 5 years of experience developing various web applications using RubyOnRails and Django but I've to tell you there's too much complexity in them but they're productive for people who are master and I think one reason that Go got too much attention was that it's easy for even juniors to master and write a simple web application or a RESTful API. But simplicity comes at a cost and using a programming language and a specific framework needs experience and dedication and choosing Go could be a wrong decision in some cases.