2

Below is a sample code , which is returning multiple values .

func (c Calc) CreateTenantHandler(item *models.TenantInput) (*models.Response, *models.ErrorDetails) {

        ...
        ...
        ...

        return &models.Response{ResponseStatus: 201, TenantOutput: tenantoutput,}, nil

    }

In test file I have tried tried doing below things.

assert.Equal(t,[nil,nil],testObject.CreateTenantHandler(nil) );

I also checked other answers but couldn't find what I need.

infiniteLearner
  • 3,555
  • 2
  • 23
  • 32

4 Answers4

5

You don't. It has nothing to do with testify--that's just how Go works. Set multiple variables to the return values, then assert each one individually:

x, y := testObject.CreateTenantHandler(nil)
assertEqual(t, x, expectedX)
assertEqual(t, y, expectedY)
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
2

The issue is that you want to convert several return values into a single value that is usable by assert.Equal.

You can do this by passing multiple values to a variadic function that converts all the values (no matter how many) into a single slice of interfaces. That slice is then treated as a single value and works quite well with testify assert.Equal.

The shim function mentioned elsewhere is close, but it has a fixed number of parameters. makeIS() below is less code, cleaner, simpler and works with any number of return values/parameters. Put this function in your test package.

    // makeIS will convert any number of parameters to a []interface{}
    func makeIS(v ...interface{}) []interface{} {
        return v
    }

Now the assert work like this

    assert.Equal(t, makeIS(eX,eY), makeIS(iReturnTwoValues())

The testify knows how to make the comparison and reports differences in the individual parameters very well. Notice this has the added benefit of "looking like" the call you want to test with the two target values to the left of the function.

Gronk
  • 149
  • 2
  • 9
0

you can add convert function to fix it

package multi_return

import (
    "github.com/stretchr/testify/assert"
    "testing"
)

func multiReturn() (int, float32) {
    return 1, 2
}

func toSlice(a ...interface{}) []interface{} {
    return a
}

func TestMultiReturn(t *testing.T) {
    assert.Equal(t, []interface{}{int(1), float32(2)}, toSlice(multiReturn()))
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
big pigeon
  • 85
  • 5
0

One simple way to do the thing you want is to declare a function like shim:

  func shim(a, b interface{}) []interface{} {
      return []interface{}{a, b}
  }

and then:

  assert.Equal(t, shim(5,6), shim(testObject.CreateTenantHandler(nil)));

The behavior is described thoroughly in the link below:

source: http://zacg.github.io/blog/2014/10/05/go-asserts-and-multiple-return-values/