在Golang单元测试中使用regex占位符的例子

222 阅读1分钟

如果你不知道你要在Golang单元测试中断言什么确切的数据,你可以使用一个重合模式的占位符,如下所示。这个例子期望一个数字ID数据作为响应体的一部分,但我们不知道它是什么,所以使用ID_REGEX 作为占位符。

package league

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"github.com/stretchr/testify/assert"
)

func TestCreate(t *testing.T) {
	// Some other code.

	requestBody := `
{
 "name": "Premier League"
}
`

	responseBody := `
{
 "operation": "leagues_post",
 "data": {
   "id": ID_REGEX
 }
}
`

	rq := httptest.NewRequest(http.MethodPost, "/leagues", strings.NewReader(requestBody))
	rw := httptest.NewRecorder()

	yourHandler.Create(rw, rq)

	// Flatten formatted json string.
	buffer := new(bytes.Buffer)
	_ = json.Compact(buffer, []byte(responseBody))

	// Replace placeholders with corresponding regex patterns.
	expectedBody := strings.ReplaceAll(buffer.String(), "ID_REGEX", "\\d+/g") // Or "\\w+" for strings, or just use ".*?" to match anything

	assert.Regexp(t, expectedBody, rw.Body.String())

	// Some other code.
}