0

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

医学类

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

异常.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;
}

我究竟做错了什么?我只是看不到错误......也许你可以。:) 当我运行程序时,我得到:“断言失败:错误,文件 ..\src/utils/../domain/testMedicine.h,第 32 行

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

4

1 回答 1

3

你不会在你的验证方法中抛出你的异常消息

和 assert(false) 中止程序执行

于 2013-04-26T15:33:36.890 回答