Home > Back-end >  Testing json.Marshal(myType) with typed parameter
Testing json.Marshal(myType) with typed parameter

Time:04-05

I have this method

func getRequestBody(object MyType ) ([]byte, error) {
    if object == nil {
        return nil, nil
    }

    requestBody, err := json.Marshal(object)
    if err != nil {
        return nil, errors.New("unable to marshal the request body to json")
    }
    return requestBody, nil
}

And I'm trying to test the function like this:

    t.Run("errorMarshaling", func(t *testing.T) {

        body, err := getRequestBody([some object of MyType to do the marshal fail])

        assert.Nil(t, body)
        assert.Equal(t, err.Error(), "unable to marshal the request body to json")
    })

Is there any way to do it without changing the function attribute type?

CodePudding user response:

json.marshall will only throw an error in specific circumstances listed in the documentation:

Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.

If the underlying object doesn't have the ability to meet one of these criteria, I don't think you'll be able to get it to fail in your test.

CodePudding user response:

Finally I changed my function parameter

type myTypeBody interface{}

func getRequestBody(object myTypeBody ) ([]byte, error) {
    if object == nil {
        return nil, nil
    }

    requestBody, err := json.Marshal(object)
    if err != nil {
        return nil, errors.New("unable to marshal the request body to json")
    }
    return requestBody, nil
}

And the test

t.Run("errorMarshaling", func(t *testing.T) {

        body, err := getRequestBody(func() {})

        assert.Nil(t, body)
        assert.Equal(t, err.Error(), "unable to marshal the request body to json")
    })
  • Related