1

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?

Prithvi singh
  • 75
  • 1
  • 6

1 Answers1

2

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:

  1. Use a test framework that does support mocking (I believe google test does).
  2. Redefine the libc functions (fprintf() and exit()) via some ugly macro hacks (#define) in the test context.
  3. Maybe you could do some ugly hack by setting up the file handle for 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.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
  • `Redefine the libc functions (fprintf() and exit()) via some ugly macro hacks (#define)` Note that on linux with `glibc` you can just mock `void exit(int status) { /* some stuff */ __libc_exit(status); }` it just like that. – KamilCuk Feb 28 '21 at 23:42
  • @EricSchaefer . Thanks for the guidance but I cannot remove the exit function. This is because this is just a dummy code to keep my question simple. The original code will lead to a segmentation fault with errors that users (my non-CS friends) cannot understand. I will try what you have suggested. **My main purpose is error-handling and write meaningful errors if the program cannot continue**. So do you know any other method of error handling please guide me. Also thanks for the help once again. – Prithvi singh Mar 01 '21 at 04:10
  • @prithvisinghtewatia What I meant is, you can call some other function that you provide which in turn calls exit, but only if you are not currently running your tests. – EricSchaefer Mar 01 '21 at 06:30
  • @EricSchaefer Google test worked. Thanks. :). Also, I got your point. – Prithvi singh Mar 01 '21 at 11:28