[fpc-pascal] Testing if exception raised in fpcUnit

Michael Van Canneyt michael at freepascal.org
Mon Nov 5 13:58:57 CET 2012



On Mon, 5 Nov 2012, ik wrote:

> On Mon, Nov 5, 2012 at 2:45 PM, Michael Van Canneyt
> <michael at freepascal.org> wrote:
>>
>>
>> On Mon, 5 Nov 2012, ik wrote:
>>
>>> Hello,
>>>
>>> I wish to test if a method has raised an exception for a value
>>> (something that should make the test pass) or not.
>>>
>>> For example:
>>>
>>> function TestNum(ch : Char) : Byte;
>>> begin
>>>  if UpCase(ch) in ['A'..'F', '0'..'9'] then
>>>    ...
>>>  else
>>>    raise Exception.Create('Invalid char was given.');
>>> end;
>>>
>>> I want to test the code with Char like 'y' for example, to make sure
>>> that it does raises the exception.
>>>
>>>
>>> Does AssertException is the proper method for such test ?
>>
>>
>> Yes.
>
> So how do I do it ?
>
> TRunMethod = procedure of object;
>
> If I pass it a function, it don't really like it:
>
> AssertException(ExceptionWasNotRaisd, EMsgPackWrongType, @MsgPackType.AsByte);

You must create a method in your testcase that calls the funtion, 
and pass that method to AssertException.

The alternative is to do everything yourself:

Procedure TMyTestClass.MyTest;

Var
   B : Byte;

begin
   try
     B:=MsgPackType.AsByte;
     Fail(ExceptionWasNotRaisd);
   except
     On E : Exception do
      if (E is not EMsgPackWrongType) then
        Fail(ExceptionWasNotRaisd);
   end;
end;

Michael.



More information about the fpc-pascal mailing list