Lab Exercise 1: Unit Testing
We will use a simple project to illustrate how to build a unit test suite.
Hello World Revisited
To illustrate unit testing, and the two styles that catch supports, refer to the hello project. In the project, we create a simple function that returns the classic “Hello World!” string. We then build unit tests (positive and negative) around the requirement that the function being tested returns the expected string value.
hello.h
#pragma once
#include <string>
namespace csc240
{
inline std::string hello()
{
return "Hello World!";
}
}
hello.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
tdd.cpp
#include "catch.hpp"
#include "hello.h"
namespace csc240
{
TEST_CASE( "Hello World function" )
{
const std::string& result = hello();
THEN( "Output should match requirement" )
{
REQUIRE( result == "Hello World!" );
REQUIRE_FALSE( result == "hello world!" );
}
}
}
bdd.cpp
#include "catch.hpp"
#include "hello.h"
namespace csc240
{
SCENARIO( "Hello World" )
{
GIVEN( "A function that generates string 'Hello World!'" )
{
const std::string& result = hello();
THEN( "Output should match requirement" )
{
REQUIRE( result == "Hello World!" );
REQUIRE_FALSE( result == "hello world!" );
}
}
}
}
Download the project to your computer. Unarchive the project and then open it with Visual Studio. Inspect the source code in the project to see how the tests are structured.