c++ - 对函数写测试用例的疑惑

标签 c++ cppunit

我在 user.cpp 中有一个函数 changeUserPassword(),我想对其进行 cppUnit 测试。

用户.cpp

int User::changeUserPassword()
{
    std::vector<user>::iterator it;
    std::ifstream readFile("info.txt");
    while(readFile >> userName >> password)
    { 
        userDetails.push_back(user(userName,password));
    }
    readFile.close();
    std::cout << "Please enter a user name that the password will be reset \n";
    std::cin >> name;
    it = std::find(userDetails.begin(),userDetails.end(),user(name,name));
    if (it !=userDetails.end())
    {
        std::cout << "Please enter a new password" << std::endl;
        std::cin >> newPassword;
        it->setPassword(newPassword);
        std::ofstream out("tempFile.txt");
        for (it =userDetails.begin(); it !=userDetails.end(); it++) {
            std::cout << it->getUserName() << " " << it->getPassword() << "\n";
            out << it->getUserName() << " " << it->getPassword() << std::endl;
        }
        out.close();
        remove("info.txt");
        rename("tempfile.txt","info.txt");
    }
    else
    {
        it++;
    }
    return 0;
}

测试用例.h

#ifndef TESTCASE_H
#define TESTCASE_H
#include "user.h"
#include <cppunit/TestCase.h>
#include <cppunit/extensions/HelperMacros.h>
class csci222TestCase : public CPPUNIT_NS::TestFixture {
    CPPUNIT_TEST_SUITE(testcase);
    CPPUNIT_TEST (testChangePassword);
    CPPUNIT_TEST_SUITE_END();
public:

protected:
    void testChangePassword(void);
private:
    user testChangeUserPassword;
};
#endif  

测试用例.cpp

void testcase::testChangePassword(void) {
   std::cout << "\n";
   CPPUNIT_ASSERT_EQUAL(testChangeUserPassword.changeUserPassword(),0);
}

问题是,我觉得我为 changeUserPassword() 编写测试用例的方式并没有测试任何东西。它更像是运行该方法,一旦它完成,它将返回 0。我应该如何或我应该做什么来改进测试用例?

最佳答案

此函数不适合进行单元测试。它具有供初学者使用的文件和用户输入。您可能真的只想测试线路

it->setPassword(newPassword);

这大概就是“设置”密码的原因。为此,您可以使用给定密码调用单元测试中的函数,然后依次执行 getPassword() 并查看它是否已更改为您预期的内容。

如果您真的想按原样测试该函数,则需要查看 stub 和/或模拟对象。为此,您需要使用一些简单的依赖注入(inject)来重构您的代码,例如,您可以将磁盘文件 I/O 与一些内存文件 I/O 交换。但我不推荐这条路。

为了解决您的概念性问题,您的 testChangePassword() 函数应该只检查密码是否已更改。就目前而言,您真正要测试的实际上是该函数不会抛出异常。

总而言之,您的单元测试理想情况下应采用以下形式:

user testuser;
testuser.setPassword( "Fred");
std::string pwd = testuser.getPassword();
CPPUNIT_ASSERT_EQUAL( "Fred", pwd);

关于c++ - 对函数写测试用例的疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21206834/

相关文章:

c++ - Opencv:如何计算 3d 直方图?

c++ - 尽管测试成功,但 CppUnit 测试核心已转储。为什么?

c++ - GoogleTest 与 CppUnit : The facts

c++ - 如何测量 CppUnit 测试覆盖率(在 win32 和 Unix 上)?

c++ - 非中止断言 CppUnit

c++ - 计算平均值最大值和最小值 C++

C# 和 C++,从 C# 调用 C++ dll 时出现运行时错误

c++ - 如何从 S 函数调用 matlab 变量?

c++ - 如何在 C++ 中使用 gRPC 同时连接到多个服务器?

unit-testing - 使用 CPPUnit 从异常中恢复