Unit Testing Introduction
Unit Testing is a structured way to test
code and highlight the coverage of our tests. If you Google unit
testing you will probably find information on unit testing
frameworks and programs, rather than a discussion on what unit
testing is.
A unit that we are testing can be many things - It could be a
whole module, a single class or a single function. In our case, we
will focus on testing individual functions on their own. So
our unit will be a single function.
Let's look at an example of a unit test. Before we begin we will
need some code to test:
Now we want to design a number of tests just for this function
that covers a good number of cases. An example of such a test,
which you could run in your main function, is:
This is a single unit test! But it only tests these two input
numbers, and we will have to verify the result manually. Let's
solve part of that by designing it a bit better:
By structuring the same test this way, we have made it easier to
verify the result because we have calculated the expected value by
hand and printed it. But we still have to check the value manually
and we will run many tests, so let's try again:
This removes the need to manually verify the test. But it is
very "noisy", since we will have many tests run and might have many
"passed" statements printed onto the terminal. However, we don't
get much information when something goes wrong! Therefore, we are
going to follow the rule that when everything is good it is
silent and when something goes wrong it is noisy, and only prints
error messages to the terminal:
We have negated/inverted the tests, so now, we only say
something when it goes wrong! We have also identified which test
failed by giving it a name in our output.
This is not the only way to structure a unit test and there are
many ways we can still improve this, but for writing tests for this
function it should be okay.
Exercise:
Copy the add function above into a file
called main-1-1.cpp. In the main function of
this program, implement a number of tests using the ideas above.
Try to design at least three unit tests for
this add function.
Unit Testing Introduction Unit Testing is a structured way to test code and highlight the coverage of our tests. If you
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
Unit Testing Introduction Unit Testing is a structured way to test code and highlight the coverage of our tests. If you
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!