2017-08-08 33 views
0

我試圖圍繞測試驅動開發與圍繞我的頭,並有一個問題測試我的CRUD功能,因爲它們是爲我的生產數據庫寫的。我來自Ruby on Rails,所以我習慣於使用測試數據庫,但Go在這方面似乎不太友善。TDD與數據庫和去

那麼,如何去Go測試CRUD?

main.go

package main 

import (
    "database/sql" 
) 

type book struct { 
    id  int  `json:"id"` 
    isbn string `json:"isbn"` 
    title string `json:"title"` 
    author string `json:"author"` 
    price float32 `json:"price"` 
} 

// type Books []*Book 

// CRUD functions for Book 
func (b *book) getBook(db *sql.DB) error { 
    return db.QueryRow("SELECT * FROM books WHERE id=$1", b.id).Scan(&b) 
} 

app.go

func (a *App) Initialize(dbname string) { 
    var err error 
    a.DB, err = sql.Open("postgres", "postgresql://localhost:5432/bookstore?sslmode=disable") 
    if err != nil { 
     log.Fatal(err) 
    } 
} 

我的測試

func TestGetBook(t *testing.T) { 
    clearTable() 
    addBook(1) 
    req, _ := http.NewRequest("GET", "/book/1", nil) 
    response := executeRequest(req) 
    checkResponseCode(t, http.StatusOK, response.Code) 
} 

問題是,這繼續看我的DB中的books表,而不是我想用於測試的books_test表。我怎樣才能讓測試只使用books_test DB?

+0

TestFoo()只運行Foo()函數。因此,當你運行測試時,你運行查詢'SELECT * FROM books WHERE id = $ 1',代碼甚至不知道數據庫中的表'book_test'。我不知道任何Ruby,所以你可能期望的是Ruby語言特有的東西。 – hbagdi

+3

你可以有兩個數據庫嗎? 'bookstore'和'bookstore_test'?在你的代碼中,如果你在生產或測試中運行,你可能會根據你的運行環境初始化連接。 (如檢查一個env變量?)? – hbagdi

+1

模擬你的數據庫,例如使用[testify's mock](https://github.com/stretchr/testify/blob/master/README.md#mock-package)。單元測試不應該針對真實的數據庫運行。這會讓你難以測試代碼對於失敗的恢復能力,併爲你的測試增加一個額外的系統。在集成測試中針對真實數據庫進行測試。 –

回答

0

您應該創建一個開發/測試數據庫,它應該是生產數據庫的完整副本。您將永遠不想直接針對您的生產數據庫運行測試,因爲可能會發生太多意外問題。

解決方法是首先啓動您的應用程序,它會創建與數據庫的連接,然後運行測試。你可以使用IntelliJ來實現這一點。

TDD在我看來非常適合開發業務邏輯層代碼,因爲新模型和業務流程可能會對現有的模型和業務流程產生意想不到的影響。

0

@ Godzilla74,there'are 2解決方案:啓用測試DB SSL(嘗試檢查數據庫設置或詢問您的系統管理員)的對測試完全不同的設置:

func (a *App) Initialize(dbname string) { 
    var err error 
    pgsettings := os.Getenv("PGSETTINGS") 
    if pgsettins == "" { 
     // default options if not overridden 
     pgsettins := "postgresql://localhost:5432/bookstore?sslmode=disable" 
    } 
    a.DB, err = sql.Open("postgres", pgsettins) 
    if err != nil { 
     log.Fatal(err) 
    } 
} 

所以,你可以設置運行環境設置爲任何所需值並運行應用程序,如下所示:

export PGSETTINGS="postgresql://localhost:5432/bookstore_test?sslmode=disable" 
go run main.go