Rhino Mock:FailedRecorded期望:IDateHelper.get_Now();

时间:2014-01-10 13:42:45

标签: c# unit-testing mocking rhino-mocks

我正在调试这个不起眼的Rhino Mocks错误:

  

Rhino.Mocks.Exceptions.ExpectationViolationException:...预期#0,   实际#1。

发现在录制前放置RhinoMocks.Logger = new TextWriterExpectationLogger(Console.Out);给了我更多信息:

  

FailedRecorded expectation:IDateHelper.get_Now();

但我不知道如何解决这个问题,甚至是什么问题。

代码如下所示:

IDateHelper dateHelper = mock.StrictMock<IDateHelper>();
DateTime now = new DateTime(2011, 12, 16);
Expect.Call(dateHelper.Now).Return(now).Repeat.Any();
...
public interface IDateHelper
    {
        DateTime Now { get; } 
    }

编辑:添加了ledbutter要求的代码。我遗漏了dateHelper被传递给另一个对象,它被传递给另一个对象......我只是不想让你们压倒我们:)我正在使用的代码库是巨大而复杂的,我没有不写; p

public IDateHelper DateHelper
    {
        get { return dateHelper ?? (dateHelper = new DateHelper()); }
        set { dateHelper = value; }
    }
...
string date = Helper.ConvertDateToYearMonth(DateHelper.Now.AddMonths(1));

当日期变量传递给另一个函数时,ExpectationViolationException会在此后发生几行。

1 个答案:

答案 0 :(得分:1)

希望这会对你有所帮助。我必须同意@ledbutter,.Expect符号是我认为更容易理解。

using System;
using NUnit.Framework;
using Rhino.Mocks;

namespace FluentConfigHelper.Test
{
    [TestFixture]
    public class StackOverflowTest
    {
        private IDateHelper _dateHelper;

        public interface IDateHelper
        {
            DateTime Now { get; }
        }

        public class DateHelper : IDateHelper
        {
            public DateTime Now { get; set; }
        }

        public IDateHelper DateHelperLocal
        {
            get { return _dateHelper ?? (_dateHelper = new DateHelper()); }
            set { _dateHelper = value; }
        }

        public DateTime MethodUnderTest()
        {
            return DateHelperLocal.Now.AddMonths(1);
        }

        [Test]
        public void DateTimeTest()
        {
            IDateHelper dateHelper = MockRepository.GenerateStrictMock<IDateHelper>();
            DateTime now = new DateTime(2011, 12, 16);
            dateHelper.Expect(x => x.Now).Return(now);
            DateHelperLocal = dateHelper;
            var result = MethodUnderTest();
            Assert.AreEqual(new DateTime(2012, 1, 16), result);
            dateHelper.VerifyAllExpectations();
        }
    }
}