From: Joe W. <joe...@us...> - 2002-10-06 21:37:48
|
Update of /cvsroot/mockobjects/nmock/sample/random In directory usw-pr-cvs1:/tmp/cvs-serv29083/sample/random Added Files: Weather.cs WeatherTest.cs Log Message: Part of the WeatherRandom sample added. --- NEW FILE: Weather.cs --- namespace NMockSample.Random { public class Weather { private WeatherRandom random; private bool isRaining = false; private double temperature = 0.0; public Weather( WeatherRandom random ) { this.random = random; } public bool IsRaining() { return isRaining; } public double GetTemperature() { return temperature; } public void Randomize() { temperature = random.NextTemperature(); isRaining = random.NextIsRaining(); if( isRaining ) temperature *= 0.5; } } public interface WeatherRandom { bool NextIsRaining(); double NextTemperature(); } public class DefaultWeatherRandom : WeatherRandom { private const double CHANCE_OF_RAIN = 0.2; private const double MIN_TEMPERATURE = 20; private const double MAX_TEMPERATURE = 30; private const double TEMPERATURE_RANGE = (MAX_TEMPERATURE-MIN_TEMPERATURE); private System.Random rng; public DefaultWeatherRandom( System.Random rng ) { this.rng = rng; } public bool NextIsRaining() { return rng.NextDouble() < CHANCE_OF_RAIN; } public double NextTemperature() { return MIN_TEMPERATURE + rng.NextDouble() * TEMPERATURE_RANGE; } } } --- NEW FILE: WeatherTest.cs --- using NUnit.Framework; using NMock; namespace NMockSample.Random { [TestFixture] public class WeatherTest { private IMock random; private Weather weather; [SetUp] public void SetUp() { random = new DynamicMock(typeof(WeatherRandom)); weather = new Weather((WeatherRandom)random.Object); } [Test] public void RandomRaining() { random.ExpectAndReturn("NextTemperature", 1.0); random.ExpectAndReturn("NextIsRaining", true); weather.Randomize(); Assertion.Assert("is raining", weather.IsRaining()); } [Test] public void RandomNotRaining() { random.ExpectAndReturn("NextTemperature", 1.0); random.ExpectAndReturn("NextIsRaining", false); weather.Randomize(); Assertion.Assert("is not raining", !weather.IsRaining()); } [Test] public void RandomTemperatureSunny() { double TEMPERATURE = 20.0; random.ExpectAndReturn("NextTemperature", TEMPERATURE); random.ExpectAndReturn("NextIsRaining", false); weather.Randomize(); Assertion.AssertEquals("temperature", TEMPERATURE, weather.GetTemperature()); } [Test] public void RandomTemperatureRaining() { double TEMPERATURE = 20.0; random.ExpectAndReturn("NextTemperature", TEMPERATURE); random.ExpectAndReturn("NextIsRaining", true); weather.Randomize(); Assertion.AssertEquals("temperature", TEMPERATURE / 2.0, weather.GetTemperature()); } } } |