I am new to unit testing and trying to understand how WillRaise works in DUnitX.
In the simple example below, there is only 1 function being tested:
it is given an integer
it expects the given integer to be positive so raises EMySimpleException if it is zero or less
otherwise, it just returns the given integer.
The first two TestCases check the return value. One of them passes and one of them fails (which is correct).
The next 2 TestCases use WillRaise to check if the correct exception is raised for a negative input.
I expect one test to pass and one to fail - but they both pass and I don't understand why.
I am assuming that I do not yet fully understand how to use WillRaise. Perhaps someone can point out my stupid error?
The code being tested:
unit MySimpleLogic;
interface
uses
System.SysUtils;
type
EMySimpleException = class(Exception)
public
constructor Create(const Msg: string); overload;
end;
TMySimpleObject = class
public
function SimpleFunctionRequiringPositiveInput(const AValue: integer): integer;
end;
implementation
{ MySimpleObject }
function TMySimpleObject.SimpleFunctionRequiringPositiveInput(const AValue: integer): integer;
begin
if (AValue <= 0) then
raise EMySimpleException.Create('Negative input not allowed');
result := Avalue;
end;
{ EMySimpleException }
constructor EMySimpleException.Create(const Msg: string);
begin
inherited Create(Msg);
end;
end.
The unit testing code:
unit TestsForMySimpleLogic;
interface
uses
System.SysUtils,
DUnitX.TestFramework,
MySimpleLogic;
type
[TestFixture]
TMyTestObject = class
private
CUT: TMySimpleObject;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
[TestCase('TestPositiveInput01','1,1')]
[TestCase('TestPositiveInput02','1,2')]
procedure TestPositiveInput(const AValue: integer; const Expected: integer);
[Test]
[TestCase('NegativeValueShouldRaiseEMySimpleException', '-1,EMySimpleException')]
[TestCase('NegativeValueShouldRaiseESomeOtherException', '-2,ESomeOtherException')]
procedure RaiseExceptionForNegativeInput(const AValue: integer; const exceptionClass : ExceptClass);
end;
implementation
procedure TMyTestObject.TestPositiveInput(const AValue: integer; const Expected: integer);
begin
var Actual := CUT.SimpleFunctionRequiringPositiveInput(AValue);
Assert.AreEqual(Expected, Actual);
end;
procedure TMyTestObject.RaiseExceptionForNegativeInput(const AValue: integer; const exceptionClass : ExceptClass);
begin
var TestMethod: TTestLocalMethod :=
procedure begin
CUT.SimpleFunctionRequiringPositiveInput(AValue);
end;
Assert.WillRaise(TestMethod, exceptionClass, 'Incorrect Exception raised');
end;
procedure TMyTestObject.Setup;
begin
CUT := TMySimpleObject.Create;
end;
procedure TMyTestObject.TearDown;
begin
CUT.Free;
end;
initialization
TDUnitX.RegisterTestFixture(TMyTestObject);
end.