单元测试:在单元测试方法中使用另一种方法时,我做对了吗? [英] Unit testing: Am I doing right when using another method in unit testing a method?

查看:72
本文介绍了单元测试:在单元测试方法中使用另一种方法时,我做对了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,应该分别对每个公共API进行单元测试.但是,我遇到的情况是我没有找到一种清晰的方法来独立地对每个API进行单元测试,如以下示例所示:

To my best knowledge, unit testing should be done on each public API separately. But, I have been experiencing with a situation in which I have not found out a clear way to unit test each API independently as shown in the following example:

class MyStorage {
private:
    std::vector<int> int_vec_;

public:
    bool insert_int(int value);
    int get_value_at(int idx);
}

我使用GooogleTest框架并编写了如下的单元测试:

I used GooogleTest framework and wrote unit tests as follows:

int int_tenth(int x) { return x * 10; }

TEST_F(MyStorageTest, insert_int) {
    for(int i = 0; i < 10; i++) {
        int value = int_tenth(i);
        bool ret = my_storage.insert_int(value);
        ASSERT_TRUE(ret);
    }
}

TEST_F(MyStorageTest, get_value_at) {
    for(int i = 0; i < 10; i++) {
        int value = int_tenth(i);
        my_storage.insert_int(value);
    }

    for(int i = 0; i < 10; i++) {
        int expected_value = int_tenth(i);
        int value = my_storage.get_value_at(i);
        ASSERT_EQ(expected_value, value);
    }
}

我做对了吗?如果没有,如何为该示例进行单元测试?

Am I doing right? If not, how can I make unit tests for this example?

推荐答案

我认为这看起来还可以".您的测试用例同时使用了两个API,是的,您需要使用insert方法来测试get方法.

I think this looks "okay". Your test case is exercising both APIs - and yes, you need to use the insert method in order to test the get method.

所缺少的是:极端情况,特别是get.像:拥有负索引的测试用例.或无效的索引.这样的测试应该导致某些错误-您可能要确保出现预期的错误(例如异常).

What is missing: corner cases, especially for get. Like: having test cases for negative indixes. Or invalid indexes. Such tests should result in certain errors - and you might want to make sure that the expected errors (for example exceptions) show up.

除此以外,您可能还想研究基于QickCheck想法的库(测试框架在其中运行随机测试,以查找违反您为生产代码指定的 properties 的行为).

Beyond that you might want to look into libraries that are based on the QickCheck idea (where the test framework runs random tests to find violations of properties that you specify for your production code).

这篇关于单元测试:在单元测试方法中使用另一种方法时,我做对了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆