我在 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/