Testing
Testing in C involves creating and executing test cases to ensure that your C code functions correctly.
Assertions
Assertions are used to check whether certain conditions are true during the execution of your program.
The assert
macro in the <assert.h>
header is a basic form of assertion in C.
#include <assert.h>
int add(int a, int b) {
return a + b;
}
int main() {
assert(add(2, 3) == 5);
return 0;
}
Frameworks
Consider using testing frameworks like Unity
or Check
to organize and automate your tests.
These frameworks provide a structure for writing and executing test cases, as well as reporting results.
Use Unity
testing framework as an example here:
#include <stdio.h>
#include <stdlib.h>
// Assume you have a header file for your calculator functions
#include "calculator.h"
// Include the Unity testing framework
#include "unity.h"
// Declare the functions to be tested
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);
// Set up initialization and cleanup functions for Unity
void setUp(void) {}
void tearDown(void) {}
// Define test cases
void test_addition(void) {
TEST_ASSERT_EQUAL_INT(5, add(2, 3));
TEST_ASSERT_EQUAL_INT(-1, add(2, -3));
// Add more test cases for addition
}
void test_subtraction(void) {
TEST_ASSERT_EQUAL_INT(-1, subtract(2, 3));
TEST_ASSERT_EQUAL_INT(5, subtract(2, -3));
// Add more test cases for subtraction
}
void test_multiplication(void) {
TEST_ASSERT_EQUAL_INT(6, multiply(2, 3));
TEST_ASSERT_EQUAL_INT(-6, multiply(2, -3));
// Add more test cases for multiplication
}
void test_division(void) {
TEST_ASSERT_EQUAL_INT(2, divide(6, 3));
TEST_ASSERT_EQUAL_INT(-2, divide(6, -3));
// Add more test cases for division
}
// Run the tests
int main(void) {
UNITY_BEGIN();
// Run test cases
RUN_TEST(test_addition);
RUN_TEST(test_subtraction);
RUN_TEST(test_multiplication);
RUN_TEST(test_division);
// End test suite
return UNITY_END();
}
Each test case uses the TEST_ASSERT_EQUAL_INT
macro to check if the actual result matches the expected result.
The setUp
and tearDown
functions can be used for any necessary setup or cleanup before and after each test.
Loading...
> code result goes here