The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

How do I test an interface? Should I even do that? | Software on a String

Posted by jpluimers on 2014/11/20

Please someone add the Software on a String blog to DelphiFeeds (:

Great article on testing implementations of interfaces in a generic way. With examples in NUnit and DUnit.

How do I test an interface? Should I even do that? | Software on a String.

And then Stefan Glienke made a great comment at https://plus.google.com/u/0/+MarjanVenema/posts/Dgb8WADLwXZ making the DUnit implementation even easier:

But even if you go without that extra base class the cool thing is that you don’t need to restrict your classes to be a TInterfacedObject but specify the interface they need to implement (yay, compiletime type safety) and then you can get rid of the Supports call and directly assign the result of the ctor call to the sut variable.

–jeroen

Stefan’s code:


// Go the full way if you are using generics :)
// Create a base class once:
TInterfaceTest<TInterface: IInterface; TImplementation: TInterface, constructor> = class(TTestCase)
protected
fSUT: TInterface;
procedure SetUp; override;
end;
{ TInterfaceTest<TInterface, TImplementation> }
procedure TInterfaceTest<TInterface, TImplementation>.SetUp;
begin
fSUT := TImplementation.Create; // cool, that works because we can combine an interface and constructor constraint and make the one generic argument the constraint for the other one!
end;
// and then you don't have to write any boilerplate code in your actual test:
TSomeInterfaceContractTests<T: ISomeInterface, constructor> = class(TInterfaceTest<ISomeInterface, T>)
published
procedure SomeMethod_Input_EmptyString_ShouldReturn_False;
end; // yes, we have to repeat the constraints here but nothing else, just write down the tests
{ TSomeInterfaceContractTests<T> }
procedure TSomeInterfaceContractTests<T>.SomeMethod_Input_EmptyString_ShouldReturn_False;
begin
CheckEquals(fSUT.SomeMethod(''), False);
end;

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.