Minimal unit testing framework for C

Related tags

Debug minunit
Overview

MinUnit

Minunit is a minimal unit testing framework for C/C++ self-contained in a single header file.

It provides a way to define and configure test suites and a few handy assertion types. It reports the summary of the number of tests run, number of assertions and time elapsed.

Note that this project is based on: http://www.jera.com/techinfo/jtns/jtn002.html

How to use it

This is a minimal test suite written with minunit:

#include "minunit.h"

MU_TEST(test_check) {
	mu_check(5 == 7);
}
MU_TEST_SUITE(test_suite) {
	MU_RUN_TEST(test_check);
}

int main(int argc, char *argv[]) {
	MU_RUN_SUITE(test_suite);
	MU_REPORT();
	return MU_EXIT_CODE;
}

Which will produce the following output:

F
test_check failed:
	readme_sample.c:4: 5 == 7


1 tests, 1 assertions, 1 failures

Finished in 0.00032524 seconds (real) 0.00017998 seconds (proc)

Check out minunit_example.c to see a complete example. Compile with something like:

gcc minunit_example.c -lrt -lm -o minunit_example

Don't forget to add -lrt for the timer and -lm for linking the function fabs used in mu_assert_double_eq.

Setup and teardown functions

One can define setup and teardown functions and configure the test suite to run them by using the macro MU_SUITE_CONFIGURE with within a MU_TEST_SUITE declaration.

Assertion types

mu_check(condition): will pass if the condition is evaluated to true, otherwise it will show the condition as the error message

mu_fail(message): will fail and show the message

mu_assert(condition, message): will pass if the condition is true, otherwise it will show the failed condition and the message

mu_assert_int_eq(expected, result): it will pass if the two numbers are equal or show their values as the error message

mu_assert_double_eq(expected, result): it will pass if the two values are almost equal or show their values as the error message. The value of MINUNIT_EPSILON sets the threshold to determine if the values are close enough.

Authors

David Siñuela Pastor [email protected]

Comments
  • Improved report for mu_assert_double_eq

    Improved report for mu_assert_double_eq

    Currently, the number of significant figures printed when mu_assert_double_eq fails is undefined. This leads to reports such as: "0.11915440 expected but was 0.11915440" whenever the accuracy in the assert is finer than the significance in printing.

    This code change causes the number of significant figures to vary with the value of MINUNIT_EPSILON. MINUNIT_EPSILON is redefined to be the additive inverse of the exponent. Conversion to 10^(-MINUNIT_EPSILON) is done by the preprocessor (avoiding the use of pow() ).

    Examples of the new behavior: MINUNIT_EPSILON=4 -> "0.1192 expected but was 0.1194" MINUNIT_EPSILON=12 -> "0.119154425113 expected but was 0.119354425113"

    opened by thomaspijper 12
  • Does not compile when using POSIX c99 command

    Does not compile when using POSIX c99 command

    This simple reference project fails to compile successfully due to minunit.c. Specifically, I get the following:

    [[email protected] kozvm]$ make
    c99 -g -O1   -c -o test/test-stack.o test/test-stack.c
    In file included from test/test-stack.c:19:0:
    test/../include/minunit.h: In function ‘mu_timer_real’:
    test/../include/minunit.h:267:19: error: storage size of ‘ts’ isn’t known
       struct timespec ts;
                       ^~
    test/../include/minunit.h:284:9: error: unknown type name ‘clockid_t’
       const clockid_t id = (clockid_t)-1; /* Unknown. */
             ^~~~~~~~~
    test/../include/minunit.h:284:25: error: ‘clockid_t’ undeclared (first use in this function); did you mean ‘clock_t’?
       const clockid_t id = (clockid_t)-1; /* Unknown. */
                             ^~~~~~~~~
                             clock_t
    test/../include/minunit.h:284:25: note: each undeclared identifier is reported only once for each function it appears in
    test/../include/minunit.h:286:31: warning: implicit declaration of function ‘clock_gettime’; did you mean ‘localtime’? [-Wimplicit-function-declaration]
       if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 )
                                   ^~~~~~~~~~~~~
                                   localtime
    test/../include/minunit.h: In function ‘mu_timer_cpu’:
    test/../include/minunit.h:330:3: error: unknown type name ‘clockid_t’; did you mean ‘clock_t’?
       clockid_t id;
       ^~~~~~~~~
       clock_t
    test/../include/minunit.h:331:19: error: storage size of ‘ts’ isn’t known
       struct timespec ts;
                       ^~
    test/../include/minunit.h:343:10: error: ‘clockid_t’ undeclared (first use in this function); did you mean ‘clock_t’?
        id = (clockid_t)-1;
              ^~~~~~~~~
              clock_t
    make: *** [<builtin>: test/test-stack.o] Error 1
    

    Part of this is due to a missing #include <sys/types.h>, but that only fixes part of the issue.

    opened by kozross 11
  • Add MU_EXIT_CODE for more reliable exit codes

    Add MU_EXIT_CODE for more reliable exit codes

    • Makes it obvious what should be used as an exit code, since before it was easy to get wrong
    • MU_EXIT_CODE uses minunit_fail instead of minunit_status because minunit_status gets reset to 0 before each test, meaning that any successful test would nullify any preceding failing tests (i.e. 4 failing tests and then a successful test case before exit would cause minunit_status to be 0 on exit)
      • Using minunit_fail also makes the exit code equal to the number of failing tests
    • Updates minunit_example.c to use MU_EXIT_CODE ~~when not in a CI env~~

    Minimal example of the minunit_status problem:

    #include "minunit.h"
    
    MU_TEST(test_fail) {
    	mu_fail("Fail now!");
    }
    MU_TEST(test_success) {
    	mu_check(1);
    }
    
    int main(int argc, char *argv[]) {
    	MU_RUN_TEST(test_fail);
    	MU_RUN_TEST(test_success);
    	MU_REPORT();
    	return minunit_status;
    }
    

    Because the successful test is run last, minunit_status would be 0 on exit. If instead the failure was last, then minunit_status would be 1 on exit. With this PR, returning MU_EXIT_CODE makes it so the order of the tests doesn't matter--if any test fails, then the exit code will be non-zero.

    (see https://github.com/squeek502/d2itemreader/commit/8695e281fd37bfbbc142acdda1dcbf40eeba21f4 for where this was causing false-positives for me)

    opened by squeek502 4
  • added string comparison mu_assert_string_eq

    added string comparison mu_assert_string_eq

    string comparison is a very useful feature for many tests. This particular one also checks if the strings are null, and replaces those with "", before doing the comparison.

    opened by spencerbug 4
  • GetSystemTimePreciseAsFileTime not found in KERNEL32.DLL

    GetSystemTimePreciseAsFileTime not found in KERNEL32.DLL

    Hello, I have a problem with a missing function in the dynamicaly loaded library (KERNEL32.DLL) on my Windows 7 machine. I thing the problem is in the line #if defined(NTDDI_WIN8) && NTDDI_VERSION > NTDDI_WIN8, This is defined as the Visual Studio shows, because of instalation of Windows 8 SDK.

    muunit

    I succesfully compiled the library with some minor changes in the header file but this works for me and I am not sure what is the best solution.

    Windows7, VS2015

    opened by groundf 3
  • Master

    Master

    This is my first ever pull request, so I do not know if the commits to my local fork (and their descriptions) are visible. In any case, below is a description for this pull request:

    The proposed code changes provide improved wallclock and CPU timers for Windows. The wallclock timer improves precision for Windows 7 and older and works on all version of Windows since 2000. The proposed CPU timer is a compacted version of the current timer (+ a small bugfix). Implementation is as recommended by Microsoft. Unfortuntately, it does not improve precision (resolution remains a mere 1/64 second) as a more precise Windows API is not available.

    opened by thomaspijper 3
  • mu_assert_double_eq not correctly printing

    mu_assert_double_eq not correctly printing

    I have code:

        ...
        
        double data = 333.0;
    
        mu_assert_double_eq(data, 1000.0);
       
        ...
    

    and minunit outputs:

    ...
    
    .F
    test_asd failed:
            ../test/test_asd.c:139: 333 expected but was 1000
    
    ...
    

    I think that the correct sentence would be ../test/test_asd.c:139: 1000 expected but was 333?

    I think the other mu_assert functions are affected by this bug.

    opened by IvanVnucec 2
  • Add syntax highlighting to readme

    Add syntax highlighting to readme

    I also converted the other two code blocks to use three backticks so that the formatting would be consistent, and I enclosed some things in inline backticks

    Original: https://github.com/siu/minunit/blob/master/README.md With changes: https://github.com/HappyFacade/minunit/blob/patch-1/README.md

    opened by HappyFacade 2
  • added utility functions: reset (to allow execution of multiple suites) enable/disable dot-progress

    added utility functions: reset (to allow execution of multiple suites) enable/disable dot-progress

    I've used the header and found the dot-progress inconvenient. It takes too much time with little added value. I also added a reset function and illustrated its usage in the example code.

    opened by cristiarg 2
  • Issue with timer types not existing

    Issue with timer types not existing

    Not sure what the exact problem is, but I had to remove the two timing functions. They were throwing errors about missing types(compile-time, not link-time) including timespec, timer_t and a few others.

    Using Arch Linux 64bit

    [[email protected] src]$ uname -a
    Linux EarlzAlpha 3.8.3-2-ARCH #1 SMP PREEMPT Sun Mar 17 13:04:22 CET 2013 x86_64 GNU/Linux
    
    [[email protected] src]$ gcc -v
    Using built-in specs.
    COLLECT_GCC=gcc
    COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/lto-wrapper
    Target: x86_64-unknown-linux-gnu
    Configured with: /build/src/gcc-4.7.2/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --disable-libstdcxx-pch --enable-libstdcxx-time --enable-gnu-unique-object --enable-linker-build-id --with-ppl --enable-cloog-backend=isl --disable-ppl-version-check --disable-cloog-version-check --enable-lto --enable-gold --enable-ld=default --enable-plugin --with-plugin-ld=ld.gold --with-linker-hash-style=gnu --disable-multilib --disable-libssp --disable-build-with-cxx --disable-build-poststage1-with-cxx --enable-checking=release
    Thread model: posix
    gcc version 4.7.2 (GCC)
    
    opened by Earlz 2
  • Add integer in array assert

    Add integer in array assert

    I have found, in a personal project that I needed to test if a value was in an array of possible values; so I added a macro that takes an array of ints and checks if the result is one of those values.

    I also updated the examples and tests to validate that it works as desired.

    opened by barrust 1
  • Support for multiple MU_TEST_SUITE() from different .c files?

    Support for multiple MU_TEST_SUITE() from different .c files?

    Would you be interested in supporting multiple MU_TEST_SUITE() from different .c files? I am offering to implement it. I know that with this MinUnit would lose the "single header file" characteristics, but I think that it is better to split tests for different modules in different files.

    opened by bzgec 1
  • Added MU_RUN_TEST_PARAMETERIZED and refactored code

    Added MU_RUN_TEST_PARAMETERIZED and refactored code

    I added the function MU_RUN_TEST_PARAMETERIZED that allows to define an array of values of the same type and a test. This test is run each time with a new value taken from the array. This should simplify some testing scenarios performing some kind of grid search.

    Since the MU_RUN_TEST and MU_RUN_TEST_PARAMETERIZED function are very similar (the same function for now, but the latter could implement a more specific error message like "the test T failed when the value was X"), i refactored the code extracting the MU_SETUP_TIMER and MU_CHECK_AND_FAIL macros.

    For now i only implemented the simple parameterized runner iterating over only 1 parameter array, but from here is trivial to add more arrays to iterate. (i can implement them myself, if needed)

    Here is an example of usage of this function:

    #include <stdio.h>
    #include <string.h>
    #include "minunit.h"
    
    int x;
    char *s;
    
    MU_TEST(simple) {
    	mu_check(x % 2 == 0);
    }
    
    MU_TEST(strings) {
    	mu_check(strlen(s) == 5);
    }
    
    MU_TEST_SUITE(suite) {
    	MU_SUITE_CONFIGURE(NULL, NULL);
    
    	int v[] = {0, 2, 4, 6};
    	MU_RUN_TEST_PARAMETERIZED(simple, x, v);
    
    	int odd[] = {1, 3, 5, 7};
    	MU_RUN_TEST_PARAMETERIZED(simple, x, odd);
    
    	char* words[] = {"hello", "world", "apple"};
    	MU_RUN_TEST_PARAMETERIZED(strings, s, words);
    }
    
    int main(int argc, char *argv[]) {
    	MU_RUN_SUITE(suite);
    	MU_REPORT();
    	return 0;
    }
    

    Note: for now i didn't find a better way to pass the values to the test function than to use global variables.

    opened by Ledmington 0
  • Added before_each and after_each

    Added before_each and after_each

    Hello, i used this library two times for my projects at university and it was absolutely a game changer. Great work! I like this library and i really want to improve it. This pull request is actually the first of a series that i'll be doing in order to add some useful features. This one adds the before_each and after_each functions, as they are called in JUnit for reference, in substitutions of setup and teardown. These two have become, respectively:

    • the function to be called before the very first test of the suite
    • the function to be called after the very last test of the suite

    I am willing to help as much as possible to improve MinUnit and my pull request, so please let me know if you want me to change anything.

    I can also provide a file with a simple example usage, if you want.

    opened by Ledmington 0
  • add mu_assert_long_eq_msg

    add mu_assert_long_eq_msg

    mu_assert_long_eq_msg allows the comparison of two longs and optionally add user-defined messages and args to the failure message.

    Or shall we can modify existing mu_assert_XXX_eqs to allow the passing of user-defined messages by default?

    opened by mkvoya 0
  • compiler warnings when in use

    compiler warnings when in use

    I got lots of warnings and they're all warnings about two lines in minunit.h

    In file included from minunit_example.c:1:
    minunit_example.c: In function ‘test_suite’:
    minunit.h:110:43: warning: comparing floating-point with ‘==’ or ‘!=’ is unsafe [-Wfloat-equal]
      110 |     MU__SAFE_BLOCK(if (minunit_real_timer == 0 && minunit_proc_timer == 0) {   \
          |                                           ^~
    minunit.h:97:9: note: in definition of macro ‘MU__SAFE_BLOCK’
       97 |         block                                                                  \
          |         ^~~~~
    
    opened by laoshaw 2
Owner
David Siñuela Pastor
David Siñuela Pastor
CppUTest unit testing and mocking framework for C/C++

CppUTest CppUTest unit testing and mocking framework for C/C++ More information on the project page Slack channel: Join if link not expired Getting St

CppUTest 1.1k Dec 26, 2022
A lightweight unit testing framework for C++

Maintenance of UnitTest++, recently sporadic, is officially on hiatus until 26 November 2020. Subscribe to https://github.com/unittest-cpp/unittest-cp

UnitTest++ 510 Jan 1, 2023
🧪 single header unit testing framework for C and C++

?? utest.h A simple one header solution to unit testing for C/C++. Usage Just #include "utest.h" in your code! The current supported platforms are Lin

Neil Henning 560 Jan 1, 2023
UT: C++20 μ(micro)/Unit Testing Framework

"If you liked it then you "should have put a"_test on it", Beyonce rule [Boost::ext].UT / μt | Motivation | Quick Start | Overview | Tutorial | Exampl

boost::ext 950 Dec 29, 2022
Simple Unit Testing for C

Unity Test Copyright (c) 2007 - 2021 Unity Project by Mike Karlesky, Mark VanderVoord, and Greg Williams Welcome to the Unity Test Project, one of the

Throw The Switch 2.8k Jan 5, 2023
A modern, C++-native, header-only, test framework for unit-tests, TDD and BDD - using C++11, C++14, C++17 and later (or C++03 on the Catch1.x branch)

Catch2 v3 is being developed! You are on the devel branch, where the next major version, v3, of Catch2 is being developed. As it is a significant rewo

Catch Org 16k Jan 8, 2023
A modern, C++-native, header-only, test framework for unit-tests, TDD and BDD - using C++11, C++14, C++17 and later (or C++03 on the Catch1.x branch)

Catch2 v3 is being developed! You are on the devel branch, where the next major version, v3, of Catch2 is being developed. As it is a significant rewo

Catch Org 16k Jan 8, 2023
The fastest feature-rich C++11/14/17/20 single-header testing framework

master branch Windows All dev branch Windows All doctest is a new C++ testing framework but is by far the fastest both in compile times (by orders of

Viktor Kirilov 4.5k Jan 5, 2023
A testing micro framework for creating function test doubles

Fake Function Framework (fff) A Fake Function Framework for C Hello Fake World! Capturing Arguments Return Values Resetting a Fake Call History Defaul

Mike Long 551 Dec 29, 2022
Googletest - Google Testing and Mocking Framework

GoogleTest OSS Builds Status Announcements Release 1.10.x Release 1.10.x is now available. Coming Soon Post 1.10.x googletest will follow Abseil Live

Google 28.7k Jan 7, 2023
C++ Benchmark Authoring Library/Framework

Celero C++ Benchmarking Library Copyright 2017-2019 John Farrier Apache 2.0 License Community Support A Special Thanks to the following corporations f

John Farrier 728 Jan 6, 2023
A C++ micro-benchmarking framework

Nonius What is nonius? Nonius is an open-source framework for benchmarking small snippets of C++ code. It is very heavily inspired by Criterion, a sim

Nonius 339 Dec 19, 2022
test framework

Photesthesis This is a small, experimental parameterized-testing tool. It is intended to be used in concert with another unit-testing framework (eg. C

Graydon Hoare 11 Jun 2, 2021
A simple framework for compile-time benchmarks

Metabench A simple framework for compile-time microbenchmarks Overview Metabench is a single, self-contained CMake module making it easy to create com

Louis Dionne 162 Dec 10, 2022
The C Unit Testing Library on GitHub is a library designed for easy unit testing in C

The C Unit Testing Library on GitHub is a library designed for easy unit testing in C. It was written by Brennan Hurst for the purpose of providing a J-Unit-like testing framework within C for personal projects.

null 1 Oct 11, 2021
Minimal unit testing framework for C

MinUnit Minunit is a minimal unit testing framework for C/C++ self-contained in a single header file. It provides a way to define and configure test s

David Siñuela Pastor 455 Dec 19, 2022
A unit testing framework for C

Check Table of Contents About Installing Linking Packaging About Check is a unit testing framework for C. It features a simple interface for defining

null 926 Jan 2, 2023
CppUTest unit testing and mocking framework for C/C++

CppUTest CppUTest unit testing and mocking framework for C/C++ More information on the project page Slack channel: Join if link not expired Getting St

CppUTest 1.1k Dec 26, 2022
A lightweight unit testing framework for C++

Maintenance of UnitTest++, recently sporadic, is officially on hiatus until 26 November 2020. Subscribe to https://github.com/unittest-cpp/unittest-cp

UnitTest++ 510 Jan 1, 2023
🧪 single header unit testing framework for C and C++

?? utest.h A simple one header solution to unit testing for C/C++. Usage Just #include "utest.h" in your code! The current supported platforms are Lin

Neil Henning 560 Jan 1, 2023