简体   繁体   English

单元测试中的细分错误

[英]Segmentation Fault in Unit test

I tested my C code with the unity function for unit test. 我用unity函数测试了我的C代码以进行单元测试。 It showed the error and a segmentation fault? 它显示错误和分段错误? Is it usual to have a segmentation fault after a unit test failure? 单元测试失败后通常会出现分段错误吗? or it is something wrong with my code? 还是我的代码有问题? Because, when I correct the error, it run successfully 因为,当我更正错误时,它成功运行

time.c

//gets start time and duration in 24 hour format and returns the total of the two in 24 hour clock


int add_time(int starttime, int duration)
{
     int startHour = starttime / 100;
     int startMinute = starttime % 100;
     int durationHour = duration / 100;
     int durationMinute = duration % 100;

     int finishHour = startHour + durationHour;
     int finishMinute = startMinute + durationMinute;

     if(finishMinute > 59)
     {
         finishMinute %= 60;
        finishHour++; 
    }

     finishHour %= 24;

     return (finishHour * 100 + finishMinute);  
}

//given end and start time, calculates the duration in 24 hour clock (duration is always less than one day) 
int duration(int endtime, int starttime)
{
     if(endtime < starttime)
         endtime += 2400;

     int endHour = endtime / 100;
     int endMinute = endtime % 100;
     int startHour = starttime / 100;
     int startMinute = starttime % 100;

     int durationMinute = endMinute - startMinute;
     int durationHour = endHour - startHour;

     if(durationMinute < 0)
     {
        durationMinute += 60;
        durationHour--;
     }

    return (durationHour * 100 + durationMinute);

}   

testtime.c 测试时间

#include "unity.h"
#include "time.c"
setUp()
{
}
tearDown()
{
}
void firstTest()
{
    TEST_ASSERT_EQUAL_INT(1, add_time(2359, 2));
    TEST_ASSERT_EQUAL_INT(1530, add_time(1215, 315));
    TEST_ASSERT_EQUAL_INT(2215, add_time(2345, 2230));
}

int main()
{
    firstTest();
    return 0;
}

It isn't correct to say that it is usual to have a segfault after a unit test fails. 说单元测试失败后通常会出现段错误是不正确的。 However, it is usual to expect seg-faults and other errors when your code is wrong. 但是, 通常在代码错误时会出现段错误和其他错误。

You can't really generalize about a segfault in relation to a particular framework or technique (unit testing in this case). 您不能真正概括出与特定框架或技术有关的段错误(在这种情况下为单元测试)。 Until you investigate the cause of the error, all you know is that the error happened. 在您调查错误原因之前,您所知道的只是该错误已发生。

Try running your incorrect code in a debugger and figuring out exactly where the segfault occurred? 尝试在调试器中运行您不正确的代码,并弄清楚段错误发生的确切位置吗? Is it in your code, or in the unit test framework? 是在您的代码中还是在单元测试框架中?

It seems you are using Unity for testing. 看来您正在使用Unity进行测试。 Try to make your main method like this: 尝试使您的主要方法如下:

int main()
{
   UNITY_BEGIN();
    if (TEST_PROTECT()) {
      RUN_TEST(firstTest);
    }
   UNITY_END();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM