开发者

how do i (unit) test my handling of runtime exceptions?

i have a small web application which does some simple data io via a gui front end.

so when the use hits 'save', the data is saved. On a runtime exception, i catch the exception, log it, and display a 'sorry etc.' label.

so as this code normally does not fail, and especially not when i want it to, there is no way for me to see if my 'sorry' label shows up and the 'succesfully saved' label is hidden.

Is there a nice solution for this?

the only way i could think of is to create a stub which throws an exception and via ioc load that stub when i want to check the 'fail' scenario's. this creates some extra work, and does not help me when i first want to test the failure of step 1, and then the succes of step 1 and the failure of step 2.

I now do it manua开发者_运维百科ly with inserting (and deleting) some throw exception commands, but that of course isn't very reliable.


what you should do is decouple the logic you are executing from the front end as much as possible. Then you can write a test which checks that the logic is executed properly independently of the UI.

You could start by writing a class which takes an object representing the data to be saved and an interface representing the dependency which will do the saving (and perhaps a interface which represents the logging dependency). Then you can write tests which pass a mock dependency which is configured to throw exceptions at the correct points, and invalid data which you can check the validation of. You could also validate that the logging was performed as you expected. This class could return an object which represents the success or otherwise of the function and you could show the message or not based on that returned object. If you are using MVC then you could validate theat the correct view is returned in the case of an error instead, but if not, then you are a bit stuck with the UI logic as far as testing goes and your only real option is to make the logic there as simple as possible.


It is indeed possible to write a test which verifies that a specific error was thrown. Look at http://www.nunit.org/index.php?p=exception&r=2.4 - the MSTest equivilant is ExpectedExceptionAttribute if that's your testing frameword :o)


Use RhinoMocks and code something like this:

    [Test]
    public void Test()
    {

        //Mocking is initialized
        MockRepository mockRepository = new MockRepository();


        //Mock of interface is created
        ISomeClass someClass = mockRepository.Stub<ISomeClass>(); 


        //Setup that the method call results in an exception being thrown.
        someClass.Stub(x=> x.DoSomeThing()).Throw(new Exception());


        //Mock is "activated"
        mockRepository.ReplayAll();


        //Here the method is called and it does indeed throw an exception
        Assert.Throws<Exception>(someClass.DoSomeThing);

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜