[fpc-pascal] fpcUnit testing Exceptions
    Dean Zobec 
    dezobec at tin.it
       
    Fri Jul 14 19:28:32 CEST 2006
    
    
  
Graeme Geldenhuys wrote:
> Hi,
> 
> Is it possible to test the code below using the AssertException()
> call?  I am sure it must be, I am just not sure how to use it.
> 
> This is the work-around I have now, untill I can figure out how to use
> AssertException() correctly.
> ------------------------
>  try
>    si.SetSlideName('006~sa.swf');
>    si.SlideTypeDB;  { <<== method raises an error if type unknown }
>  except
>    on E: exception do
>    begin
>      AssertEquals('Failing on 3', EUnknownSlideType.ClassName,
> E.ClassName);
>    end;
>  end;
> ------------------------
> 
> I tried the following, but got a compiler error on each one.
> 
> -----------------------------
>  si.SetSlideName('006~sa.swf');
>  { none of the following worked... }
>  AssertException('Failing on 3', EUnknownSlideType, @si.SlideTypeDB);
>  AssertException('Failing on 3', EUnknownSlideType, si. at SlideTypeDB);
>  AssertException('Failing on 3', EUnknownSlideType, si.^SlideTypeDB);
> -----------------------------
from the FPCUnit code:
class procedure AssertException(const AMessage: string; AExceptionClass:
ExceptClass; AMethod: TRunMethod); overload;
where
TRunMethod = procedure of object;
How is SlideTypeDB defined?
the correct way should be
AssertException('Failing on 3', EUnknownSlideType, @si.SlideTypeDB);
provided SlideTypeDB is a simple procedure with no parameters
and you are using
{$mode objfpc}
See the examples and the tests in the fcl/fpcunit directory on how to
use AssertException
Btw, there is an elegant way to test that a proper exception is raised
without using AssertException e.g. (from fcl/fpcunit/tests/asserttest.pp):
procedure TAssertTest.TestAssertNull;
var
  obj: TObject;
begin
  AssertNull(nil);
  obj := TObject.Create;
  try
    AssertNull(obj);
  except
    on E: EAssertionFailedError do
    begin
      obj.Free;
      Exit;
    end;
  end;
  obj.Free;
  Fail('failure: obj is not null!');
end;
Ciao,
Dean
    
    
More information about the fpc-pascal
mailing list