How to use ThrowTheSwitch's Unity C unit testing library?

1.6k views Asked by At

How to use ThrowTheSwitch's Unity C unit testing library?

I'm trying to use ThrowTheSwitch's Unity library to create my unit test in C, but I got some strange errors, but I'm newbie, so this is maybe something basic.

Here is My code: this is mytest.c

int testValue = 45;

int testThisPass(int idx)
{
    if idx == 42
        return 1;
    
    return 0;
}

int testThisNotPass(int idx)
{
    return 42;
} 

this is mytest.h

int testThisPass(int idx);
int testThisNotPass(int idx);

this is mytestMain.c

#include "unity.h"
#include "unity_internals.h"
#include "mytest.h"
#include <stdio.h>

void setUp(void) {
    //testValue = 40;
}

void tearDown(void) {
    // clean stuff up here
}

void test_function_should_doBlahAndBlah(void) {
    TEST_ASSERT_EQUAL(1,testThisPass(42));
}

void test_function_should_doAlsoDoBlah(void) {
    TEST_ASSERT_EQUAL(42, testThisNotPass(5));
}

// not needed when using generate_test_runner.rb
int main(void) {
    UNITY_BEGIN();
    RUN_TEST(test_function_should_doBlahAndBlah);
    RUN_TEST(test_function_should_doAlsoDoBlah);
    return UNITY_END();
}

And this is the error what I got when I tried to compile mytestMain.c:

/usr/bin/ld: /tmp/ccOOjz1w.o: in function `test_function_should_doBlahAndBlah':
mytestMain.c:(.text+0x24): undefined reference to `testThisPass'
/usr/bin/ld: mytestMain.c:(.text+0x43): undefined reference to `UnityAssertEqualNumber'
/usr/bin/ld: /tmp/ccOOjz1w.o: in function `test_function_should_doAlsoDoBlah':
mytestMain.c:(.text+0x58): undefined reference to `testThisNotPass'
/usr/bin/ld: mytestMain.c:(.text+0x77): undefined reference to `UnityAssertEqualNumber'
/usr/bin/ld: /tmp/ccOOjz1w.o: in function `main':
mytestMain.c:(.text+0x8e): undefined reference to `UnityBegin'
/usr/bin/ld: mytestMain.c:(.text+0xa6): undefined reference to `UnityDefaultTestRun'
/usr/bin/ld: mytestMain.c:(.text+0xbe): undefined reference to `UnityDefaultTestRun'
/usr/bin/ld: mytestMain.c:(.text+0xc3): undefined reference to `UnityEnd'
collect2: error: ld returned 1 exit status

What Should I do to work? What did I missed here?

2

There are 2 answers

0
Nisal Dissanayake On

There are two ways,

  1. Build Unity as a separate static library. And link with it when you build your test executable.
    • provide linker flag -lunity
  2. Build your test executable together with "unity.c".
    • gcc mytestMain.c mytest.c ./unity/src/unity.c -o Example ./TestExample
0
Vince Molnar On

The problem was that I linked in the unity with them. when I include it, it works.