【问题标题】:Where to put main and what to write there?主要放在哪里,在哪里写什么?
【发布时间】:2013-04-18 08:26:06
【问题描述】:

我在文件tested.cpp 中有以下代码:

#include <iostream>
using namespace std;

class tested {
    private:
        int x;
    public:
        tested(int x_inp) {
            x = x_inp;
        }

        int getValue() {
            return x;
        }
};

我还有另一个文件(称为testing.cpp):

#include <cppunit/extensions/HelperMacros.h>
#include "tested.cpp"

class TestTested : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE(TestTested);
    CPPUNIT_TEST(check_value);
    CPPUNIT_TEST_SUITE_END();

    public:
        void check_value();
};

CPPUNIT_TEST_SUITE_REGISTRATION(TestTested);

void TestTested::check_value() {
    tested t(3);
    int expected_val = t.getValue();
    CPPUNIT_ASSERT_EQUAL(7, expected_val);
}

当我尝试编译 testing.cpp 文件时,我得到:undefined reference tomain'`。嗯,这是因为我没有 main(程序的入口点)。所以,编译器不知道如何开始执行代码。

但我不清楚如何执行testing.cpp 中的代码。我尝试添加:

int main() {
        TestTested t();
        return 1;
}

但是,它不打印任何内容(并且由于 3 不等于 7,因此预计会返回错误消息)。

有人知道运行单元测试的正确方法是什么吗?

【问题讨论】:

  • 1.您不应该包含“*.cpp”文件和 2. 创建对象会调用 check_value 方法吗?可能需要调用其他方法来开始测试...
  • 您不应包含 cpp 文件,而应包含 h/lib 文件。总之 main 的第一行是声明一个函数
  • 但是我只有一个cpp文件。如果我不包含它,我的testing.cpp 将不知道tested.cpp 中声明的内容。
  • @Roman Infested 备注的第二部分非常重要:您需要将t 声明为TestTested t;,而不是TestTested t();。即,删除圆括号。这很重要。它完全改变了声明的含义。

标签: c++ main


【解决方案1】:

既然你正在编写一个 cppunit 测试,为什么不看 cppunit doc 呢? (http://cppunit.sourceforge.net/doc/lastest/cppunit_cookbook.html)

它告诉你主要的灵魂应该是这样写的:

#include <cppunit/ui/text/TestRunner.h>
#include "ExampleTestCase.h"
#include "ComplexNumberTest.h"

int main( int argc, char **argv) {
  CppUnit::TextUi::TestRunner runner;
  runner.addTest( ExampleTestCase::suite() );
  runner.addTest( ComplexNumberTest::suite() );
  runner.run();
  return 0;
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 2014-03-10
    • 2012-09-22
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 2015-03-20
    相关资源
    最近更新 更多