Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a static function

Tags:

c

unit-testing

As applying unit-test to some C code, we run into a problem that some static function can not be called at the test file, without modifying the source code. Is there any simple or reasonable way to overcome this problem?

like image 364
Kevin Yu Avatar asked Feb 27 '09 03:02

Kevin Yu


People also ask

How do you test the static method?

All you need to do is wrap the static method call inside an instance method and then use dependency injection to inject an instance of the wrapper class to the class under test.

How do you write a test case for a static method?

Note that you should add the class that contains static methods in two places in your unit tests: On top of the unit test class using @PrepareForTest annotation. In your test setup by calling the PowerMockito. mockStatic to do the necessary initialization step before trying to mock any of its methods.

How do you use a static function?

Static Function MembersBy declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.


2 Answers

I have a test harness. In dire cases - like trying to test a static function, I use:

#include "code_under_test.c" ...test framework... 

That is, I include the whole of the file containing the function under test in the test harness. It is a last resort - but it works.

like image 102
Jonathan Leffler Avatar answered Sep 22 '22 15:09

Jonathan Leffler


Can you give more information as to why you can't call the function?

Is it not available because it's private to a .c file? If so, you're best bet is to use conditional compilation that allows for access to the function in order to allow for other compilation units to access it. For example

SomeHeaderSomewher.h

#if UNIT_TEST #define unit_static  #else #define unit_static static #endif 

Foo.h

#if UNIT_TEST void some_method #endif 

Foo.cpp

unit_static void some_method() ... 
like image 42
JaredPar Avatar answered Sep 19 '22 15:09

JaredPar