試用CppUnit--一個簡單的例子

用CppUnit其它與用Junit差不多,基本原理是一致的,不過我以爲,與Junit相比,配置它稍微麻煩了一點.
(下一篇文章,將介紹cppunit在vc6.0及vc.net下的配置)


我以一個簡單的Money類爲例

//name:money.h

#ifndef MONEY_H
#define MONEY_H


#include <string>

class Money
{
public:
  Money( double amount)
    : m_amount( amount )
  {
  }

  double getAmount() const
  {
    return m_amount;
  }

private:
  double m_amount;
};


#endif

我們現在需要用Cppunit來測試它的這兩個函數-----構造函數和getAmount()函數.

第一步:當然是配置cppunit環境了,這裏就不多說了(下面講的環境是在vc下的)
第二步:利用嚮導建立一個console application,名字爲MoneyApp,編輯項目內的MoneyApp.cpp如下:
// MoneyApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>


int main(int argc, char* argv[])
{
  // Get the top level suite from the registry

  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();

  // Adds the test to the list of test to run
  CppUnit::TextUi::TestRunner runner;
  runner.addTest( suite );

  // Change the default outputter to a compiler error format outputter
  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
                                                       std::cerr ) );
  // Run the tests.
  bool wasSucessful = runner.run();

  // Return error code 1 if the one of test failed.

  return wasSucessful ? 0 : 1;
}

第三步:現在纔到了我們爲Money類寫測試的時候了,我們首先新建一個頭文件MoneyTest.h,其內容如下:
#ifndef MONEYTEST_H
#define MONEYTEST_H

#include <cppunit/extensions/HelperMacros.h>

class MoneyTest : public CppUnit::TestFixture
{
  //其實就是在這裏面加入要測試的項目
  CPPUNIT_TEST_SUITE( MoneyTest );
  CPPUNIT_TEST( testGetAmount );
  CPPUNIT_TEST_SUITE_END();

public:
  void setUp();
  void tearDown();


  void testConstructor();
  void testGetAmount();
};


#endif  // MONEYTEST_H

然後,我們再新建一個cpp文件MoneyTest.cpp,(對了,真正的測試正是在這裏面),其內容如下:
#include "stdafx.h"
#include "MoneyTest.h"
#include "Money.h"

//這句很重要,應與前面的"CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest()"對照起來看
// Registers the fixture into the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION( MoneyTest );

void
MoneyTest::setUp()
{
 
}


void
MoneyTest::tearDown()
{
}

void
MoneyTest::testConstructor()
{

}

void
MoneyTest::testGetAmount()
{
 const double longNumber = 12345678.90123;
 Money money ( longNumber);

 CPPUNIT_ASSERT_EQUAL( longNumber,money.getAmount());
}
第四步:好了,可以按ctrl+F5跑一下了,運行結果是這樣:

.

OK (1)
Press any key to continue

如果想看一看斷言失敗是什麼效果的話,可以這樣:
把CPPUNIT_ASSERT_EQUAL( longNumber,money.getAmount());
改爲CPPUNIT_ASSERT_EQUAL( 100,money.getAmount());
則運行結果就是這樣.
.F

D:/ZHANGYD/MoneyApp/MoneyTest.cpp(38):Assertion
Test name: MoneyTest::testGetAmount
equality assertion failed
- Expected: 100
- Actual  : 1.23457e+007

Failures !!!
Run: 1   Failure total: 1   Failures: 1   Errors: 0
Press any key to continue

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章