Alex K.
Alex K.

Reputation: 103

Go: How can I create an instance of type schema.ResourceData with values for unit testing?

I want to write a unit test for a method similar to this:

package bingo

import "github.com/hashicorp/terraform-plugin-sdk/helper/schema"

func doStuff(d *schema.ResourceData) error {
    foo := d.Get("foo").(string)
    // ... operations using d
    return nil
}

Is there a way to create an instance of type schema.ResourceData with values in it?

I tried creating a "blank" instance of ResourceData and populate it via .Set(...). But it doesn't work, since no schema is present:

package bingo

import "github.com/hashicorp/terraform-plugin-sdk/helper/schema"

func TestDoStuff(t *testing.T) {
    d := schema.ResourceData{}
    err := d.Set("foo", "bar")
    if err != nil {
      t.Errorf("failed to set value: %s", err)
      // > failed to set value: Invalid address to set: []string{"foo"}
    }

    // test doStuff()
}

Upvotes: 3

Views: 579

Answers (1)

Alex K.
Alex K.

Reputation: 103

schema.TestResourceDataRaw does exactly that:

package bingo

import "github.com/hashicorp/terraform-plugin-sdk/helper/schema"

var testSchema = map[string]*schema.Schema{
    "foo": {Type: schema.TypeString}
}

func TestDoStuff(t *testing.T) {
    d := schema.TestResourceDataRaw(t, testSchema, map[string]interface{
        "foo": "bar",
    })
    err := doStuff(d)
    if err != nil {
        t.Fail()
    }
}

Link to the documentation

Thanks to @mkopriva for pointing out the builtin helper method.

Upvotes: 2

Related Questions