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
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

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Leveraging Test Containers With Docker for Efficient Unit Testing
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects
  • Improving Java Code Security

Trending

  • Next-Gen Lie Detector: Stack Selection
  • Outsmarting Cyber Threats: How Large Language Models Can Revolutionize Email Security
  • Tenv v2.0: The Importance of Explicit Behavior for Version Manager
  • Building an Effective Zero Trust Security Strategy for End-To-End Cyber Risk Management
  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
Like (2)
Save
Tweet
Share
9.5K 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

  • Leveraging Test Containers With Docker for Efficient Unit Testing
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects
  • Improving Java Code Security

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: