unit-testinggotesting

How to unit test for multipart.Form


I need to write tests for that function:

func Parse(f *multipart.Form) ([]Person, error)

It's important to say, that multipart.Form.Value is not just key:value, thats more complicated json, simple example:

[
    {
        "value": {
            "person_name__0": "Mike",
            "person_name__1": "John"
        },
        "question": {
            "id": 52681363,
            "slug": "person_name"
        }
    },
    {
        "value": {
            "created_date__0": "2024-06-26",
            "created_date__1": "2024-06-24"
        },
        "question": {
            "id": 52681362,
            "slug": "created_date"
        }
    },
    {
        "value": "Germany",
        "question": {
            "id": 52681360,
            "slug": "country"
        }
    }
]

What is the best way to test that func? Should I create json files(or just json strings in code) manually, make from them multipart.Form objects or should I create such files automatically(I believe this is a hard one)? Or I can somehow create mock objects? But how can I create mock multipart.Form objects, that will have the same .Value structure(I mean same json structure, like in my example)?

Thats my first try to test something, may be there's stupid questions, but I hope you can tell me whats wrong and help me out=)


Solution

  • Use text. Keep it simple.

    func TestExample(t *testing.T) {
    
        data := `--XXX
    Content-Disposition: form-data; name="text"
    
    a text value
    --XXX
    Content-Disposition: form-data; name="file"; filename="a.txt"
    Content-Type: text/json
    
    [
        {
            "value": {
                "person_name__0": "Mike",
                "person_name__1": "John"
            },
            "question": {
                "id": 52681363,
                "slug": "person_name"
            }
        },
        {
            "value": {
                "created_date__0": "2024-06-26",
                "created_date__1": "2024-06-24"
            },
            "question": {
                "id": 52681362,
                "slug": "created_date"
            }
        },
        {
            "value": "Germany",
            "question": {
                "id": 52681360,
                "slug": "country"
            }
        }
    ]
    --XXX--`
    
        form, err := multipart.NewReader(strings.NewReader(data), "XXX").ReadForm(1024 * 1024)
        if err != nil {
            t.Fatal(err)
        }
        people, err := Parse(form)
        // Check for expected values here.
    
    }