V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
AkideLiu
V2EX  ›  程序员

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

  •  
  •   AkideLiu · 2020-10-03 02:08:26 +08:00 · 1514 次点击
    这是一个创建于 1308 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 )

    3 条回复    2020-10-03 23:31:30 +08:00
    lcdtyph
        1
    lcdtyph  
       2020-10-03 03:02:10 +08:00   ❤️ 2
    如果是用 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
        2
    reus  
       2020-10-03 10:28:20 +08:00 via Android
    你应该针对 stream 做测试,这样就不需要理会是标准输入流还是文件流还是其他什么流
    AkideLiu
        3
    AkideLiu  
    OP
       2020-10-03 23:31:30 +08:00
    @reus 怎么准队 stream 做测试呢,大佬给个想法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2186 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:16 · PVG 19:16 · LAX 04:16 · JFK 07:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.