CException to try catch invalid memory access.

154 views
Skip to first unread message

Felipe Moura Oliveira

unread,
Aug 24, 2021, 4:37:56 PM8/24/21
to ThrowTheSwitch Forums
Hello all,

I'm new to unit tests and using Unity. 
I could apply unity with ceedling with my embedded project without some problems, just process properly asserts give me work.

I used - http://www.electronvector.com/blog/unit-testing-with-asserts - tutorial to test my assert implementations.

Now I'm trying to detect if any function does no have "assert" and needs it. It is possible using CException?

For example:
pic.png

pic2.png

But seems that the "Try" statement can't "bypass" this kind of fault.
This is a limitation of CException or I'm doing something wrong?

My out:
pic3.png

Tnx very much.

Joe Trainor

unread,
Aug 27, 2021, 9:31:58 AM8/27/21
to ThrowTheSwitch Forums
Hello,

Did you add the following to top of your source code to redirect the assert so it uses Cexception of the system assert?

#ifdef TEST
#undef assert
#include "CException.h"
#define assert(condition) if (!(condition)) Throw(0)
#endif

Then your source code can look like this:

#include <assert.h>

#ifdef TEST
#undef assert
#include "CException.h"
#define assert(condition) if (!(condition)) Throw(0)
#endif

void foo(struct mystruct_t* mystruct) {
    // Assert when a null pointer is detected.
    assert(NULL != mystruct);
    
    // Do something with the struct.
    mystruct->a = 1;
    mystruct->b = 2;
}

Attached is helper include file for writing tests.  It makes it easier to test for asserts.  Add '#include "assert_unit_test_support.h"' to top of your test source file.  I usually place the helper include file in the support folder.  Then your test code can look like this:

#include "unity.c"

#inlcude "assert_unit_test_support.h"
#include "../inc/test.h"

void setUp(void)
{
    // your setup code
}

void tearDown(void)
{
    // your tear down code
}


void test_foo_asserts_on_null_struct(void)
{
    // code should assert for NULL pointers
    struct mystruct_t * null_struct = NULL;
    TEST_ASSERT_FAIL_ASSERT(foo(null_struct));
    
    // code should not assert for non-NULL pointers
    struct mystruct_t valid_struct;
    TEST_ASSERT_PASS_ASSERT(foo(&valid_struct));
}

Hope this helps.
assert_unit_test_support.h
Reply all
Reply to author
Forward
0 new messages