如何使用Visual Studio CppunittestFramework访问我的代码



我希望单元测试我的代码。这是我完成的任务的专有步骤,即我已经编写的代码。

我正在使用VS Community 2017 v.15.9.7。我遵循本网站的指示,按行逐行:https://blogs.msdn.microsoft.com/vcblog/2017/04/19/cpp-testing-in--visual-studio/#setup

,但毕竟我得到了两个错误:

1)错误lnk1120 1未解决的外部unittest1 source repos primes debug debug unittest1.dll 1

2)错误lnk2019未解决的外部符号" public:bool __ thiscall searchprimes :: isprime(int)"(?isprime@searchprime@qae_nh@z)void)"(?isodd@testClass@unittest1 @@ qaexxz)unittest1 c: Users users velzevoul source source primes primes unittest1 unittest1.obj

我尝试了移动文件,但是我的事情随机移动它们会造成的弊大于利。我在"源"中读到了有关" stdafx.h"的信息,但随着更多的错误不断弹出。

这是我写的代码的标题文件:

#pragma once
#include <vector>
#include "XMLParser.h"
class SearchPrimes 
{
public:
    std::vector<int> RangePrime(const std::pair<int, int>&);     
    //Setting the range to search for prime numbers, executing the algorithm
    bool IsPrime(int);  //The algorithm that checks if a number is prime
    bool IsOdd(int);    //Checking if a number if even or odd
};

#pragma once
#include <iostream>
#include <vector>

class XMLParser
{
public:
    void removeTags(std::string&);  //Removing the brackets of the tags of the .xml

    std::string openFile(std::string);  //Opening a file
    std::vector<std::string> readFile(const std::string&, std::string); 
   //Getting the text from the .xml file to a vector
    std::vector<std::pair<int, int> > stringsToInts();  
   //Finding the values of the tags that contain the ranges
   //and converting the string numbers to a vector<int>
};  

这是test.cpp

#include "stdafx.h"
#include "CppUnitTest.h"
#include "/Users/Velzevoul/source/repos/Primes/Primes/SearchPrimes.h"
#include "/Users/Velzevoul/source/repos/Primes/Primes/XMLParser.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{       
    TEST_CLASS(TestClass)
    {
    public:
        TEST_METHOD(IsOdd)
        {
            SearchPrimes prime;
            Assert::IsTrue(prime.IsPrime(4));
        }
    };
}

为了解决外部依赖关系,我该怎么办?文章说,一旦我遵循我可以开始的步骤。正如文章所暗示的那样,该测试是在一个单独的项目中。如果您认为问题可能与我的main()函数有关,请告诉我包括它。我现在不这样做,因为它很漫长。

我感谢您提前的时间!

该文章建议您可以按照DLL的方式链接到Windows可执行文件。我想如果已经设置了可执行文件来导出其功能,从理论上讲这是可能的,但是这似乎是一件奇怪的事情。

有两种选择用于访问C 单元测试项目中测试的代码:

  1. 将源模块(.cpp/.h)添加到您的单元测试项目。
  2. 与包含代码的库链接。

如果您的项目相对简单,只有几个.CPP模块,则选项1可能是要走的方法。右键单击单元测试项目,选择"添加 ->现有项目...",然后添加您要测试的.cpp模块。

对于具有许多源模块的更复杂的项目,选项2可能是一个更好的选择。创建一个或多个库项目(静态或动态)以包含您的源模块,然后将可执行文件和单元测试项目与库链接。

一个好的做法是为要测试的每个项目创建一个单元测试项目。给单元测试项目一个名称,指示正在测试的项目,即MyExecutableMyExecutable.TestMyLibraryMyLibrary.Test等。

最新更新