How to test error case in golang with "entgo.io/ent"

120 views Asked by At

I am writing go code in a project using ent, and wondering if there are any ways to test specific error block thrown by Save.

Does anyone know good practice to do this?

test target code example (from: ent/examples/start/start.go)

func CreateCars(ctx context.Context, client *ent.Client) (*ent.User, error) {
    tesla, err := client.Car.
        Create().
        SetModel("Tesla").
        SetRegisteredAt(time.Now()).
        Save(ctx)

    if err != nil {
        return nil, fmt.Errorf("failed creating car: %w", err)
    }

    ford, err := client.Car.
        Create().
        SetModel("Ford").
        SetRegisteredAt(time.Now()).
        Save(ctx)

    if err != nil {
        // I want to test this block.
        return nil, fmt.Errorf("failed creating car: %w", err)
    }

    a8m, err := client.User.
        Create().
        SetAge(30).
        SetName("a8m").
        AddCars(tesla, ford).
        Save(ctx)

    if err != nil {
        return nil, fmt.Errorf("failed creating user: %w", err)
    }

    return a8m, nil
}

test code example

t.Run("method returns error as expected", func(t *testing.T) {
    user, err := CreateCars(ctx, client)

    // test error message begin with "failed creating car:" here
})
1

There are 1 answers

0
Stark Sim On

If you want the Save() method throws an error, you may do something incorrect to the database. For example, set the same Car.ID manually and let it duplicate.