单元测试学习笔记 之三

发表于:2011-8-24 13:29

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

  第三章 单元测试的工具——测试框架

  3.1 常用的单元测试框架

  工欲善其事,必先利其器。程序员在写单元测试代码时,如果能借助一些单元测试框架,那么使单元测试代码的书写、维护、分类、存档、运行和结果检查变得更为容易,从而成倍地提高工作效率。在本章中,我们就将学习两种单元测试的框架。

  第一种,就是鼎鼎大名的xUnit测试框架家族。xUnit测试框架有助于我们更加结构化地书写测试代码,更方便地运行单元测试并检查运行结果。

  第二种框架称为隔离框架(isolation framework)。这种框架旨在帮助程序员自动地生成FakeCollaboratorClass代码。但是隔离框架一般都要求ClassUnderTest依赖于CollaboratorService抽象接口,而不是具体类CollaboratorClass,所以在使用“Virtual and Override”手法时,隔离框架就帮不忙了,必须由程序员手写FakeCollaboratorClass的代码。

  在接下来的几个小节中,我们将针对C++,C#和Java语言,分别介绍适用于它们的单元测试框架。

  3.2 用于C++的单元测试框架

  对于C++,我们推荐使用Google C++ Unit Testing Framework(简称gTest, 目前为1。5版)加HippoMocks(目前为3。1版)的组合。如下的表格演示了如何使用这两个框架。

  gTest的基本用法

  声明Test Fixture

#ifndef CLASS_UNDER_TEST_TEST_H
#define CLASS_UNDER_TEST_TEST_H
// In [ClassUnderTest]Test.h file.
#include <gtest/gtest.h>
// Test Fixture declaration.
class [ClassUnderTest]Test : public testing::Test
{
protected:
    // Optional SetUp() and TearDown().
    virtual void SetUp();
    virtual void TearDown();
};
#endif

  定义Test Method

// In [ClassUnderTest]Test.cpp file.
#include <gtest/gtest.h>
#include <hippomocks.h>
#include "[ClassUnderTest]Test.h"
// Optional SetUp() and TearDown().
void [ClassUnderTest]Test::SetUp()
{
    ...
}
void [ClassUnderTest]Test::TearDown()
{
    ...
}
// Test Method definition.
TEST_F([ClassUnderTest]Test, [Feature]_[Scenario]_[ExpectedBehavior])
{
    ...
}

// Temporarily ignore a test case.

TEST_F([ClassUnderTest]Test, DISABLE_[Feature]_[Scenario]_[ExpectedBehavior])
{
    ...
}

  Test Runner

// Currently, gTest only supports CUI. The main() should be like this.
#include <gtest/gtest.h>
#include "[ClassUnderTest]Test.h"
int main(int argc, char** argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

51/512345>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号