I am trying to test a method, which in turn calls another method.
Which is something like the folloing
public string mainmethod()
{
string val = submethod();
... do more ...
}
I am using NUnit and I do not want the submethod execute to get the
'val' I want some way to fake the value that is coming from that
method and continue with the rest of mainmethod process. Is there a
way to do it in NUnit?
The submethod has some expensive process that is running that I don't
want to initialise or execute.
Thanks,
Here is how I would go about doing this. There is probably a good
reason why submethod shouldn't get executed in test. Think about
moving this method into another class. If you are hitting a database
or whatever, separating the logic from persistence is just good
practice. Once you have your new class, create an interface for it.
"Okay", you're saying. Your simple method call just became another
class and _now_ its also got an interface.
It gets worse. Now, you have to create a stub that implements your
interface. You must pass this stub into the class your testing. This
means you may need to change your class to take the submethod
interface as a ctor argument or as an argument to mainmethod.
interface submethod_interface { string submethod(); }
class submethod_production : submethod_interface { public string
submethod() { return "Production"; } }
class submethod_test : submethod_interface { public string submethod()
{ return "Test"; }}
[TestMethod]
public void TestMainMethod()
{
submethod_test stub = new submethod_test();
MyClass myClass = new MyClass(stub);
myClass.mainmethod();
}
Now the implementation for MyClass should be obvious.
class MyClass
{
submethod_interface _smi;
MyClass(submethod_interface smi) {_smi = smi;}
void mainmethod() { string value = _smi.submethod(); }
}
This whole process is called dependency injection. It makes large-
scale testing possible. It also has a wonderful habit of being a good
heuristic for design. By forcing your code to pass dependencies, you
get good cohesion and low coupling automatically.
In a small application, dependency injection can cause more work than
its worth. In this case, I usually create stubs for the ADO .NET
classes: IDbConnection, IDbCommand, IDataReader, etc. Then you can
call your database methods all day, the stubs just ignore them. But
this means your code has to support the general-purpose System.Data
classes and not the SQL Server-, Oracle-, etc.-specific classes (which
may be a good thing).
If you don't want to implement a bunch of stubs, a library like NMock
can come in handy. It will create some stubs automatically and record
the number of times and the order that stubbed methods were called.
Everything I learned was from the book: xUnit Test Patterns. It is a
long and redundant read, but well worth the effort if you're going to
write large-scale programs that are actually tested.
![Smile :-) :-)](/styles/default/custom/smilies/smile.gif)