Re: Testing for errors
"Charlie Poole" <[email protected]>
| Newsgroups | gmane.comp.windows.dotnet.nunit.user |
|---|---|
| Message-ID | <002801c8725b$96094740$6401a8c0@ferrari> |
Hi Christian,
> The situation is as follows: Let's say I have a Vector class with an
> accessor-method:
>
> Element at (int index);
>
> This method's contract says that the index must be in the range [0,
> size()-1]. If it's not, it's an error. -- And this is what
> I'd like to
> test. So in the test I'd like to write something like this:
>
> [Test]
> void at_errorIfIndexOutOfRange()
> {
> // setUp Vector v with some elements
> int outOfRange = -1;
> Assert.IsError (v.at (outOfRange));
> }
>
> The Assert.IsError() is something I would like to implement.
> But I don't
> know how.
> The error-case is communicated via an exception (a special
> DeveloperError-exception). But this is an implementation detail and I
> don't want to expose that to neither the implementor of the
> method nor
> the user of the interface nor the implementor of the test. Just to
> illustrate: the implementation could look something like this:
>
> Element at (int index)
> {
> Asserter.ensure (index >= 0 && index < size(), "Index out
> of range.");
> // ...
> return e;
> }
>
> So the DeveloperError-exception-stuff is hidden behind
> Asserter.ensure() and
> Assert.IsError()
>
> Any ideas how to implement such a beast?
Of course, you could use try/catch but that would expose the implementation
to the test. As a side note, this doesn't bother most of us - the test is
supposed to have knowledge of the external implementation of the methods
it tests and any exception is part of that.
You could also use an ExpectedException attribute, like this...
> [Test, ExpectedException(typeof(DeveloperError-exception))]
> void at_errorIfIndexOutOfRange()
> {
> // setUp Vector v with some elements
> int outOfRange = -1;
> v.at (outOfRange);
> }
To wrap the processing in an assert as you outlined, the problem
is that exception is thrown as soon as the argument is evaluated
and the IsError method is never called. The way around this is
to use a delegate, either explicit or anonymous depending on the
version of .NET you are using.
IMO, this is a bit involved for the case as described... I'd just
test for the exception, but it's certainly possible if you really
want to.
Charlie
-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/