ThrowTheSwitch / Unity

Simple Unit Testing for C

Home Page:ThrowTheSwitch.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add __FILE__ to failure messages.

informatimago opened this issue · comments

The source of failure messages is not always just the test driver source.
So we need to add __FILE__ to the failure messages to track the right point where a failure macro is called.

Hi. The goal is to always report the line of the test that triggered the failure. That isn't to say that creating shared helper functions, etc isn't helpful, but it's less helpful when done incorrectly. I suspect, if you're posting this, you're in a situation where you have a mismatch of information... you're seeing the test file and the line number for your helper function or customer assertion.

When creating helpers and such, which use assertions in other files, use the macros starting with UNITY_TEST_. This is similar to the TEST_ macro, but you provide the line number and the message always. These macros are the building blocks for all the other variations.

Let's say I wanted to create my own assertion and it tests the following:

typedef struct SPOON_T_
{
    int8_t roundedness;
    int length;
} SPOON_T;

In my own file, I create a function like this:

void AssertEqual_SPOON_T(const SPOON_T expected, const SPOON_T actual, int line) 
{
    UNITY_TEST_ASSERT_EQUAL_INT8(expected.roundedness, actual.roundedness, line, "Roundedness values were not equal");
    UNITY_TEST_ASSERT_EQUAL_INT(expected.length, actual.length, line, "Length values were not equal");
}

#define UNITY_TEST_ASSERT_EQUAL_SPOON_T(e, a, line, msg) AssertEqual_SPOON_T(e, a, line)
#define TEST_ASSERT_EQUAL_SPOON_T(e, a) AssertEqual_SPOON_T(e, a, __LINE__)

The second macro is the one you'd use in your own tests. It'll properly report the file and line in the test which failed, but still provide enough detail to let you know what part of your test failed.

The first macro is there because it matches the format that CMock expects. If you tell CMock you have a helper file and point it at the file containing this macro, it'll automatically recognize this format and will let you mock functions which take SPOON_T arguments. Instead of using the default memory assertions, it'll now use your custom assertion with the better reporting.

Not all helper files are just creating assertions. Sometimes they're reusing custom test logic, etc... In these cases, you're going to find that it's more useful to know where in your test you failed, rather than some mysterious assertion in another file.

When that isn't true, it's a very good sign that you're probably putting too much abstraction into your tests and they're becoming as hard to debug as your source code. That's to be avoided, for obvious reasons. ;)

I hope this helps!