我创建了一个类和一个验证器,所以我想使用断言为验证器做一些测试。这就是我所说的:
类医学
class Medicine{
private:
int ID;
string name;
public:
Medicine(){
this->ID=0;
this->name="";
}
Medicine(int ID, string name, float concentration, int quantity){
this->ID=ID;
this->name=name;
}
~Medicine(){};
//inline get methods
int getID(){
return ID;
}
string& getName(){
return name;
}
//inline set methods
void setID(int newID){
this->ID = newID;
}
void setName(string newName){
this->name = newName;
}
};
exceptions.h
#include <string>
using namespace std;
#include <string>
using namespace std;
class MyException
{
public:
MyException(string msg):message(msg){}
const string& getMessage() const {return message;}
private:
string message;
};
class ValidatorException: public MyException
{
public:
ValidatorException(string msg): MyException(msg){}
};
class RepositoryException: public MyException
{
public:
RepositoryException(string msg): MyException(msg){}
};
药物治疗师
#include "exceptions.h"
#include "medicine.h"
class MedicineValidator{
public:
void validate(Medicine& m) throw (ValidatorException);
};
#include "medicineValidator.h"
void MedicineValidator::validate(Medicine& m) throw (ValidatorException){
string message="";
if(m.getID()<1){
message+="The ID should be positive and >0!";
}
if(m.getName()==""){
message+="The name field is empty, and it shouldn't!";
}
if(m.getConcentration()<1){
message+="The concentration should be positive(>0)!";
}
if(m.getQuantity()<1){
message+="The quantity should be positive(>0)!";
}
}
测试验证器的算法:
void testValidator(){
Medicine* m = new Medicine(1,"para",30,40);
MedicineValidator* medValidator = new MedicineValidator();
medValidator->validate(*m);
m->setID(-2); //the ID should not be < 1 so it should catch the exception but the test fails
try{
medValidator->validate(*m);
assert(false);
}
catch(ValidatorException& ex){
assert(true);
}
delete m;
}
我做错了什么?我只是看不出错误......也许你可以。 :)当我运行程序时,这就是我得到的:“断言失败:false,文件.. \ src / utils /../ domain / testMedicine.h,第32行
此应用程序已请求Runtime以不寻常的方式终止它。 请联系应用程序的支持团队获取更多信息。“
答案 0 :(得分:3)
您不会在验证方法中抛出异常消息
和assert(false)中止程序执行