验证器的断言失败

assertion fails for validator

本文关键字:失败 断言 验证      更新时间:2023-10-16

我创建了一个类和一个验证器,所以我想对验证器使用断言进行一些测试。这就是我说的:

类药

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){}
};

medicineValidator

#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行

这个应用程序请求运行时以一种不寻常的方式终止它。请联系应用程序的支持团队获取更多信息。"

不要在validate方法中抛出异常消息

和assert(false)中止程序执行