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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Selecting the Right Automated Tests
  • Supercharging Productivity in Microservice Development With AI Tools
  • Mastering Node.js: The Ultimate Guide
  • Improving Customer-Facing App Quality Using Tricentis Testim

Trending

  • Creating a Deep vs. Shallow Copy of an Object in Java
  • What Is Good Database Design?
  • Build a Digital Collectibles Portal Using Flow and Cadence (Part 1)
  • Agile Estimation: Techniques and Tips for Success
  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.

Alan Hohn user avatar by
Alan Hohn
·
Dec. 13, 15 · Tutorial
Like (2)
Save
Tweet
Share
8.93K 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

  • Selecting the Right Automated Tests
  • Supercharging Productivity in Microservice Development With AI Tools
  • Mastering Node.js: The Ultimate Guide
  • Improving Customer-Facing App Quality Using Tricentis Testim

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: