Ok, I have an Nunit test class setup that runs though a method, lets all it CalcBalance(). Within CalcBalance() we have another method that will save things to a database. I do not want to deal with the database when testing this particular method, but when I run my tests the database method throws an exception and causes the test to fail because the databases isn’t setup/mocked. Example:
CalcBalance()
{
//Stuff I want to test
DatabaseInteraction() //Throws exception
return; //This is the value I want to have tested.
}
My question is, is there any way I can set this up so that the Nunit tester will continue to test through even though the database interaction is saying it failed. I commented out DatabaseInteraction() and ran the test and it went through fine.
The functionality inside
DatabaseInteractionwhich is causing the exception should be abstracted out to another class which implements an interface. This interface can then be mocked for use in unit testing.For example:
Then in the unit test, it can be done like this (using Moq):
The
IDatabaseInteractionis mocked to do nothing, so there is no chance of an exception or any unrelated functionality taking place.For further information, read up on Inversion of Control, it is really useful for testability.