Reputation: 75
Hello everyone I am new to Cunit.My question is below the code so you may skip it if you want to. I made a small function that adds two positive integers and returns the result and if any of the integers is less than or equal to zero then it writes to stderr an error message.
/*This file is dummy.c*/
#include "dummy.h"
int add(int a,int b)
{
if(a<=0||b<=0)
{
fprintf(stderr,"Error in arguments");
exit(EXIT_FAILURE);
}
else
return a+b;
}
This is dummy.h
#include<stdio.h>
#include<stdlib.h>
int add(int a,int b)
This is a part of my CUnit test code. Filename is testdummy.c
/*Necessary files have been included*/
void addtest()
{
CU_ASSERT_EQUAL(add(3,5),8);
CU_ASSERT_EQUAL(add(1,6),7);
/*What should I add here*/
}
What should I add in the section specified so that my code is also tested for error messages?
Upvotes: 1
Views: 316
Reputation: 26370
The error case in your code is a tough one. It is not designed to be tested. It calls a libc function directly and, to make matters worse, is calling exit()
. IIRC CUnit does not support mocking libc functions. Therefore I see two and a half possibilities:
fprintf()
and exit()
) via some ugly macro hacks (#define
) in the test context.fprintf()
in a way that you can read the output to assert on it. But then you are still left with that exit()
call.Learn about mocking and how to write testable code. Your code is hard to test. It doesn't have to be.
Upvotes: 2