tags:

views:

37

answers:

1

I made the following test for my class:

var mock = new Mock<IRandomNumberGenerator>();
mock.Setup(framework => framework.Generate(0, 50))
    .Returns(7.0);

var rnac = new RandomNumberAverageCounter(mock.Object, 1, 100);
rnac.Run();
double result = rnac.GetAverage();
Assert.AreEqual(result, 7.0, 0.1);

The problem here was that I changed my mind about what range of values Generate(int min, int max) would use. So in Mock.Setup() I defined the range as from 0 to 50 while later I actually called the Generate() method with a range from 1 to 100.

I ran the test and it failed. I know that that is what it's supposed to happen but I was left wondering if isn't there a way to launch an exception or throw in a message when trying to run the method with wrong params.

Also, if I want to run this Generate() method 10 times with different values (let's say, from 1 to 10), will I have to make 10 mock setups or something, or is there a special method for it? The best I could think of is this (which isn't bad, I'm just asking if there is other better way):

for (int i = 1; i < 10; ++i) {
    mock.Setup(framework => framework.Generate(1, 100))
        .Returns((double)i);
}
A: 

Have you looked at the Moq QuickStart? I suspect you want the It.IsAny mechanism and/or one of the Returns overloads wherewith you supply a lambda method that gets called back to generate and/or match/validate params into the mocked method.

Ruben Bartelink