0

Im trying to mock a method, it compiles without errors, but smth strange happens when i run a test. Actually method doesnt mock or maybe I dont understand smth...(

Here's a code:

public class Robot
{   ....

    public virtual bool range(IObs ob, double range)
    {
        double dist = ob.distanceSq(this);
        if (dist < range)
            return true;
        else
            return false;
    }
}

...

public interface IObs
{
    double distanceSq(Robot r);
}

...

Unit Test:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        MockRepository mocks = new MockRepository();
        IObs obstacleMock = mocks.CreateMock<IObs>();
        Robot r = new Robot();
        Expect.Call(obstacleMock.distanceSq(r)).IgnoreArguments()
           .Constraints(Is.Anything())
            .Return(5.5);
        Assert.IsTrue(r.range(obstacleMock, 0.5));
    }
}

I mock distanceSq(). When I debug my test, i see that ob.distanceSq(this) is 0.0. (not 1.5).

What's wrong?

  • @GrantWinney - using `deciaml` probably is not useful in this case - `double` should be more than enough for most distance computations. – Alexei Levenkov May 29 '13 at 20:54

2 Answers2

0

Your code does not actually use mock you created - as you can change Obstacle to IObjs as argument of range and than pass mock instead of new instance of Obstacle:

public virtual bool range(IObjs ob, double range)....
class Obstacle : IObjs ...

Assert.IsTrue(r.range(obstacleMock, 0.5));
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

I would recommend that you upgrade your RinoMocks version to 3.6 and use the new syntax.

Additionally if you are using a mock for IObs, you may as well verify that the distanceSq method is called.

I have left the verification of the parameters in the distanceSq method out of this code, but you could ensure that the correct Robot instance is passed in.

The unit test will still fail however, as 5.5 is greater than 0.5

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

namespace Rhino
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var r = new Robot();
            var obstacleMock = MockRepository.GenerateMock<IObs>();
            obstacleMock.Expect(x => x.ditanceSq(Arg<Robot>.Is.Anything)).Return(5.5);
            //use this line to ensure correct Robot is used as parameter
            //obstacleMock.Expect(x => x.ditanceSq(Arg<Robot>.Is.Equal(r))).Return(5.5);
            var result = r.range(obstacleMock, 0.5);
            obstacleMock.VerifyAllExpectations();
            Assert.IsTrue(result);
        }
    }

    public class Robot
    {
        public virtual bool range(IObs ob, double range)
        {
            return  ob.ditanceSq(this) < range;         
        }
    }

    public interface IObs
    {
        double ditanceSq(Robot r);
    }
}
MikeW
  • 1,568
  • 2
  • 19
  • 39