douwang4374 2019-03-17 15:49
浏览 14

如何模拟依赖于其他方法的方法

I am testing an elasticsearch middleware. It implements a reindex service like this

type reindexService interface {
    reindex(ctx context.Context, index string, mappings, settings map[string]interface{}, includes, excludes, types []string) error
    mappingsOf(ctx context.Context, index string) (map[string]interface{}, error)
    settingsOf(ctx context.Context, index string) (map[string]interface{}, error)
    aliasesOf(ctx context.Context, index string) ([]string, error)
    createIndex(ctx context.Context, name string, body map[string]interface{}) error
    deleteIndex(ctx context.Context, name string) error
    setAlias(ctx context.Context, index string, aliases ...string) error
    getIndicesByAlias(ctx context.Context, alias string) ([]string, error)
}

I can easily test all the methods using this pattern. Creating a simple elastic search client using a httptest server url and making requests to that server

var createIndexTests = []struct {
    setup *ServerSetup
    index string
    err   string
}{
    {
        &ServerSetup{
            Method:   "PUT",
            Path:     "/test",
            Body:     `null`,
            Response: `{"acknowledged": true, "shards_acknowledged": true, "index": "test"}`,
        },
        "test",
        "",
    },
   // More test cases here
}

func TestCreateIndex(t *testing.T) {
    for _, tt := range createIndexTests {
        t.Run("Should successfully create index with a valid setup", func(t *testing.T) {
            ctx := context.Background()
            ts := buildTestServer(t, tt.setup)
            defer ts.Close()
            es, _ := newTestClient(ts.URL)
            err := es.createIndex(ctx, tt.index, nil)
            if !compareErrs(tt.err, err) {
                t.Fatalf("Index creation should have failed with error: %v got: %v instead
", tt.err, err)
            }
        })
    }
}

But in case of reindex method this approach poses a problem since reindex makes calls to all the other methods inside its body. reindex looks something like this:

func (es *elasticsearch) reindex(ctx context.Context, indexName string, mappings, settings map[string]interface{}, includes, excludes, types []string) error {
    var err error

    // Some preflight checks

    // If mappings are not passed, we fetch the mappings of the old index.
    if mappings == nil {
        mappings, err = es.mappingsOf(ctx, indexName)
        // handle err
    }

    // If settings are not passed, we fetch the settings of the old index.
    if settings == nil {
        settings, err = es.settingsOf(ctx, indexName)
        // handle err
    }

    // Setup the destination index prior to running the _reindex action.
    body := make(map[string]interface{})
    body["mappings"] = mappings
    body["settings"] = settings

    newIndexName, err := reindexedName(indexName)
    // handle err

    err = es.createIndex(ctx, newIndexName, body)
    // handle err

    // Some additional operations

    // Reindex action.
    _, err = es.client.Reindex().
        Body(reindexBody).
        Do(ctx)
    // handle err

    // Fetch all the aliases of old index
    aliases, err := es.aliasesOf(ctx, indexName)
    // handle err
    aliases = append(aliases, indexName)

    // Delete old index
    err = es.deleteIndex(ctx, indexName)
    // handle err

    // Set aliases of old index to the new index.
    err = es.setAlias(ctx, newIndexName, aliases...)
    // handle err

    return nil
}

I was thinking about mocking the functions used by reindex and somehow injecting them into the es struct so that mocks are called inside of reindex but the original reindex function should be called since I want the original function to be covered by my tests.

I have read a lot of articles about mocking and DI but I still can't wrap my head around this problem. For e.g. if I have a mock es struct like this that implements the same interface and I want to use that while testing the reindex method

type mockES struct {
    url    string
    client *elastic.Client
}

func newMockElasticsearch(url string) (*mockES, error) {
    client, err := elastic.NewSimpleClient(elastic.SetURL(url))
    if err != nil {
        return nil, fmt.Errorf("error while initializing elastic client: %v", err)
    }
    es := &mockES{
        url:    url,
        client: client,
    }
    return es, nil
}

func (m *mockES) mappingsOf(ctx context.Context, index string) (map[string]interface{}, error) {
    return m.mockMappingsOf(ctx, index), nil
}

func (m *mockES) mockMappingsOf(ctx context.Context, index string) map[string]interface{} {
    // return some pre-defined response
}

What I can't understand is that if I call a reindex defined on mockES then only I will be able to use these mock methods but I would like to call the original reindex method defined on the elasticsearch struct and the calls to the other methods be made to the mock ones.

Is it possible to acheive it given the state of how the codebase is implemented currently or will I have to change the design of my implementation in order to be able to write tests for it?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
    • ¥15 对于squad数据集的基于bert模型的微调
    • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
    • ¥20 steam下载游戏占用内存
    • ¥15 CST保存项目时失败
    • ¥15 树莓派5怎么用camera module 3啊
    • ¥20 java在应用程序里获取不到扬声器设备
    • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
    • ¥15 Attention is all you need 的代码运行
    • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗