Mock question?

  • Thread starter Thread starter Ilyas
  • Start date Start date
I

Ilyas

Hi all

Not sure if this is the right group, I am happyo to repost to correct
group if I know what that is! but in the mean time - here goes

I am using NMock2 and I have question.

I have the following interface:

public interface ITime
{
int Hour { get; }
}

and the following weather service:

public class WeatherService:ITime
{
public string GetTodaysWeather()
{
if (Hour >= 0 && Hour <= 6)
{
return "Sunny";
}
else if (Hour >= 7 && Hour <= 15)
{
return "Foggy";
}
else
{
return "Snowing";
}
}

public int Hour
{
get { return DateTime.Now.Hour; }
}
}

In order for me to test this I have created the simple test:

[Test]
public void CanGetSunnyWeather()
{
Mockery m = new Mockery();
ITime mockObject = m.NewMock<ITime>();


Stub.On(mockObject).GetProperty("Hour").Will(Return.Value(2));

WeatherService ws = new WeatherService();
Assert.AreEqual("Sunny", ws.GetTodaysWeather());
m.VerifyAllExpectationsHaveBeenMet();
}

This fails as the Hour Property on Weather service doesnt get mocked
and I expected it to. Why is this? I want to be able to test this
weather servce without relying on the time which is why I mocked it -
but it doesnt behave as expected any ideas anyone?
 
Hi

maybe I'll not answer your question. But in the end you might still end
up with a solution.

In my opinion you should create a class TimeProvider that implements
your interface ITime. You then add an instance to your WeatherService.

You also want to provide a setter for the timeProvider. You might also
want to provide a Constructor WeatherService(ITime timeProvider) to set
the timeProvider at construction time.

You can then use either a fake implementation FakeTimeProvider, which
always returns 2 for the hour, that is added to your WeatherService or
you can use NMock to mock this TimeProvider.

Hope this helps

Al.

ps: untested code

public interface ITime
{
int Hour { get; }
}

public class TimeProvider : ITime
{
public int Hour
{
get { return DateTime.Now.Hour; }
}
}

public class WeatherService
{
ITime timeProvider;

// --- provide a setter if you want to change timeProvider
// after construction

WeatherService(ITime timeProvider)
{
this.timeprovider = timeProvider;
}

public string GetTodaysWeather()
{
// you get the idea
}
}
 
hi

to answer your question. Your mock is actually never called. Use my
earlier advice to fix it

Al.
 
Back
Top