mercredi 22 avril 2020

Fail test at specific DB operation

How can I go about writing extensive tests for this kind of function?

I guess what I want to test is: What happens if the database or the database connection cuts off in the middle of a function?

func Do(database *db.DB) error {

    // because of this preceding setup, DB Operation 1, 2 and 3 will always
    // have good data
    if err := setUpWithGoodData(); err != nil {
        return err
    }

    if err := DBOperation1(database); err != nil {
        return fmt.Errorf("operation 1 failed: %w", err)
    }

    if err := DBOperation2(database); err != nil {
        return fmt.Errorf("operation 2 failed: %w", err)
    }

    if err := DBOperation3(database); err != nil {
        return fmt.Errorf("operation 3 failed: %w", err)
    }
}

This is what I want to test, but how can I when DBOperation1, 2 and 3 will always have good data? Is it even possible?

func TestDo(t *testing.T) {
    t.Run("returns expected error when DBOperation1 fails", func(t *testing.T) {
        assert.Contains(t, Do(testDB).Error(), "operation 1 failed")
    })

    t.Run("returns expected error when DBOperation2 fails", func(t *testing.T) {
        // here DBOperation1 should pass, but 2 should fail
        assert.Contains(t, Do(testDB).Error(), "operation 2 failed")
    })

    t.Run("returns expected error when DBOperation3 fails", func(t *testing.T) {
        // here DBOperation1 and DBOperation 2 should pass, but 3 should fail
        assert.Contains(t, Do(testDB).Error(), "operation 3 failed")
    })
}

Aucun commentaire:

Enregistrer un commentaire