I’m new to unit test and confusing how write unit test method like this:
public Boolean BeepInTime(Interfaces.IDateTime time,TimeSpan beepTime)
{
Interfaces.IBeep beep= new Beep();
var h = time.GetTime();
if (h == beepTime)
{
return beep.Beeping();
}
else
{
return false;
}
}
public Boolean Beeping()
{
try
{
SystemSounds.Beep.Play();
return true;
}
catch
{
return false;
}
}
When testing BeepInTime , I’d like (beep.Beeping()) not running. I read about stub and think in this case I should use stub but it is confusing about how to do this.
Could you send some source with simple example about stub.
The solution is – dependency injection.
Each time you do or see
... = new ...();(construction) think of dependency injection, basically explicit instantiation introduces dependencies and then sometimes writing unit tests for such a code becomes not trivial.So instead of explicit instantiation of
Beepclass just inject it. What is good – you already have an interface which abstracts this class –IBeep, this would allow you creatign and injecting a mock instead of a real class instance when writing unit tests.Ans just imagine how this technique is helpful in case of injecting DB access service or web-service, you do not need a real DB or web-service while writing unit tests – you just mock DB/web service and that’s it.
Example using RhinoMocks: