简体   繁体   中英

Rhino Mocks doesnt mock a method

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?

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));

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM