All Topics
All Topics
Technology
Technology
AI
AI
Business
Business
Entertainment
Entertainment
News
News
Programming
Programming
Science
Science
Design
Design
Environment
Environment
Finance
Finance
Crypto
Crypto
Politics
Politics
Sports
Sports
Education
Education
Gaming
Gaming
Art
Art
Music
Music
Health
Health
Security
Security
Books
Books
Food
Food
Travel
Travel
Personal
Personal
Bluesky
Twitter

Golang Function Driven Tests

7y agoen

Source

jdx.devGolang Function Driven Testsjdx.dev
Snippet from the RSS feed
Dave Cheney had a fantastic post on improving test structure in Go code with table-driven tests. I want to expand on it just a tiny bit to show how table-driven tests can be made more concise with functions. If you haven’t read his article, read that before continuing. The end result of Dave’s post is the following example: func TestSplit (t * testing.T) { tests := map [ string ] struct { input string sep string want [] string }{ "simple" : {input: "a/b/c" , sep: "/" , want: [] string { "a" , "b" , "c" }}, "wrong sep" : {input: "a/b/c" , sep: "," , want: [] string { "a/b/c" }}, "no sep" : {input: "abc" , sep: "/" , want: [] string { "abc" }}, "trailing sep" : {input: "a/b/c/" , sep: "/" , want: [] string { "a" , "b" , "c" }}, } for name, tc := range tests { got := Split (tc.input, tc.sep) if !reflect. DeepEqual (tc.want, got) { t. Fatalf ( "%s: expected: %v, got: %v" , name, tc.want, got) } } } This is a nice way to reduce code duplication, but closing over a new function we can go one step further

You might also wanna read

Comments

Sign in to join the conversation.

No comments yet. Be the first.