DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot
  • Understanding the Two Schools of Unit Testing

Trending

  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • Agile and Quality Engineering: A Holistic Perspective
  • How Trustworthy Is Big Data?
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Covering Error Cases in Go Unit Tests

Covering Error Cases in Go Unit Tests

Zone Leader Alan Hohn continues his coverage of unit testing in the Go programming language.

By 
Alan Hohn user avatar
Alan Hohn
·
Dec. 13, 15 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
9.9K Views

Join the DZone community and get the full member experience.

Join For Free

In a previous article I showed table-driven tests in Go, which are a compact way to run lots of test cases. In this article I will show another way to improve unit tests in Go: table-driven tests with invalid values.

To illustrate this, I've created an example library in Go that converts Roman numerals in string form to their numeric value. Of course, not all strings are valid Roman numerals. In Go, functions typically return an error value rather than throwing an exception. However, this is not done using "special" return values as in C; instead, functions return multiple values, one of which is an error value that is non-nil if an error occurred. Go provides an error type for use in these cases.

Here is an example from the Go blog:

func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, errors.New("math: square root of negative number")
    }
    // implementation
}

The (float64, error) indicates that the function returns both a value of type float64 and a value of type error. If the error value is non-nil, the primary return value should be ignored.

Users of this function should check the error on return:

result, err := Sqrt(-1.0)
if err != nil {
    // Don't use the result
    fmt.Println("I sent a bad input")
}

In a unit test, we want to ensure that errors that should be returned are returned. To do this, we can again leverage a table-driven test, with the input and the expected error.

For example:

var invalidTests = []struct {
    input    string
    expected error
}{
    {"XXXX", ErrInvalidFormat},
    {"VV", ErrInvalidFormat},
    {"VX", ErrInvalidFormat},
}

The test code looks like this:

func TestInvalid(t *testing.T) {
    for _, tt := range invalidTests {
        res, err := RomanToInt(tt.input)
        if err == nil {
            t.Errorf("Expected error for input %v but received %v", tt.input, res)
        }
        if err != tt.expected {
            t.Errorf("Unexpected error for input %v: %v (expected %v)", tt.input, err, tt.expected)
        }
    }
}

In the example library I simplified this since all cases resulted in the same error.

Similar to our previous use of table-driven tests, this allows us to add test cases quickly and to easily see what error is expected for a given input. As before, we need to be careful when logging any test failure to make sure we indicate which test case failed and what we were expecting instead; otherwise debugging becomes very difficult.

Now that we can test both normal and error cases, we can cover our entire Roman numeral function. In the next article I will show how to turn that excellent unit test code coverage into a green badge on a GitHub repository.

unit test

Opinions expressed by DZone contributors are their own.

Related

  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot
  • Understanding the Two Schools of Unit Testing

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!