assert 宏用于单元测试

需求 在单元测试中,需要能够自动判断结果和预期是否相符,如果不符,就报错。 解决 可以直接参考 st 的 assert_param 宏,根据需要,自己改造下,增加了额外的自定义错误说明语句。 // assert #include <stdint.h> #ifdef USE_ASSERT #define ASSERT_FAIL(expr, msg) ((expr) ? (void)0U : assert_fail((char*) msg, (char*)__FILE__, __LINE__)) void assert_fail(char* msg, char* file, uint32_t line); #else #define ASSERT_FAIL(expr) ((void)0U) #endif /* USE_ASSERT */ #ifdef USE_ASSERT void assert_fail(char* msg, char* file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ //SEGGER_RTT_printf(0, "assert_failed: file %s on line %d", file, line); Log::printf(Log::kError, "assert_failed1: file %s on line %d\n", file, line); while(1); } #endif /* USE_ASSERT */ void CurrentAverageTest() { ASSERT_FAIL((1 == 1), "CurrentAverageTest, result 1 error"); } 只要在编译参数中,增加 USE_ASSERT, 开启,即可使用宏来自动判断结果是否相符。...

2023-06-21 · 1 min · 117 words · RamLife