所以我想尝试TDD并将CppUnit设置为测试环境。我想从小处开始阅读食谱。我只想测试类Factor的公共阶乘函数。我的测试运行成功,但是程序突然核心转储,我不知道为什么。我在Ubuntu 18.04 64位和CppUnit 1.14上使用g ++。
testmain.cpp
#include "test1.h"
int main(){
CppUnit::TestCaller <Test1> test ("test", &Test1::testFactorial );
CppUnit::TestSuite suite;
suite.addTest(&test);
CppUnit::TextUi::TestRunner runner;
runner.addTest(&suite);
runner.run( );
return 0;
}
test1.h
#ifndef TEST1_H
#define TEST1_H
#include <cppunit/TestAssert.h>
#include <cppunit/TestCase.h>
#include <cppunit/TestFixture.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestResult.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestSuite.h>
#include "factorial.h"
class Test1 : public CppUnit::TestFixture {
private:
Factor *f_6;
public:
void setUp(){
f_6 = new Factor();
}
void tearDown(){
//to see whether my variable gets freed
std::cout << "delete testvariable\n";
delete f_6;
}
void testFactorial(){
int f6 = f_6->factorial(6);
CPPUNIT_ASSERT(f6 == 720);
}
};
#endif
factorial.h
#ifndef FACTORIAL_H
#define FACTORIAL_H
class Factor{
public:
int factorial(int arg){
int result = 1;
for(int i = 1; i <= arg; i++){
result *= i;
}
return result;
}
};
#endif
命令行输出:
user@computer:~/folder$ make test
g++ -g -Wall -o testexecutable testmain.cpp -lcppunit
user@computer:~/folder$ ./testexecutable
.delete testvariable
OK (1 tests)
free(): invalid size
Aborted (core dumped)
user@computer:~/folder$
为什么在执行测试用例时会有这种奇怪的自由和核心转储?
答案 0 :(得分:2)
CppUnit测试套件删除析构函数中的所有测试对象。因此,您需要在主测试中分配测试,而不是直接在堆栈中使用测试。
类似地,我认为TestRunner也会进行清理,因此您也需要分配TestSuide对象。
在以下位置查看“ Suite”和“ TestRunner”标题: http://cppunit.sourceforge.net/doc/cvs/cppunit_cookbook.html
因此您的主要人员变为:
class Account(models.Model):
name = models.CharField(max_length=100)
budget = models.IntegerField()
slug = models.SlugField(max_length=100, blank=True)
def save_account(self):
self.save()
def budget_left(self):
expense_list = Expense.objects.filter(account = self)
total_expense = 0
for expense in expense_list:
total_expense += expense.amount
return self.budget - total_expense
class ExpenseCategory(models.Model):
account = models.ForeignKey(Account, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
class Expense(models.Model):
account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="expense")
title = models.CharField(max_length=100)
amount = models.DecimalField(max_digits=8, decimal_places=2)
category = models.ForeignKey(ExpenseCategory, on_delete=models.CASCADE)
class Meta:
ordering = ('-amount',)