请教 c++如何测试用户的输入, input testing

2020-10-03 02:08:26 +08:00
 AkideLiu

C++小白,最近写的小 demo 用到了 Gtest 的 unit test 大多数的 function

但是当主函数根据用户的输入( cin )来传值给 function 的时候如何测试呢?

暂时想到的方法就是把需要输入的内容用 txt 文件进行保存,然后用./executable < input.txt 的方式进行比模拟用户输入。

大概测试思路如下:

https://stackoverflow.com/questions/11408020/c-testing-with-input-cases-from-text-files

然后写成 shell 脚本:

EXEFile=$(find "$(pwd -P)"  -name 'GTestSelfInput' | head -1)

cd $CURRENT_DIR

$EXEFile --gtest_filter=People_Services_input.initPassword01 < input1.txt

if [ $? != "0" ]; then
    exit 1
fi

然后通过不同模拟的 input.txt 传入的参数再使用 Gtest 去确认操作是否成功。

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);

    return RUN_ALL_TESTS();
}

//init password successes
TEST(People_Services_input, initPassword01) {

    Storage::setSUserId(1);
    EXPECT_TRUE(PeopleServices::initPassword());

    People *p = PeopleDao::selectOnePeople(1);

    EXPECT_EQ(p->getPassword(), "password123");

    mysql::connection db = database_connection::getConnection();

    db.execute("UPDATE oop.people t SET t.password = '-1' WHERE t.user_id = 1;");

    delete p;

}

但是这样有很大的局限性,比如没办法随机生成输入内容,使用起来也非常不方便。

有没有什么测试框架可以解决这样的问题呢?( system testing,functional testing )

1531 次点击
所在节点    程序员
3 条回复
lcdtyph
2020-10-03 03:02:10 +08:00
如果是用 std::cin 做输入的话可以覆盖它的 rdbuf

```
#include <iostream>
#include <sstream>

int main() {

std::string fake_input = "abc";
std::istringstream iss{fake_input};

std::cin.rdbuf(iss.rdbuf());

std::string a;
std::cin >> a;
std::cout << a << std::endl;

return 0;
}
```
reus
2020-10-03 10:28:20 +08:00
你应该针对 stream 做测试,这样就不需要理会是标准输入流还是文件流还是其他什么流
AkideLiu
2020-10-03 23:31:30 +08:00
@reus 怎么准队 stream 做测试呢,大佬给个想法

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/712301

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX