部分模拟测试在从Mocked方法调用调用的私有方法中调用失败

时间:2012-02-06 12:53:05

标签: rhino-mocks partial-mocks

下面,我有一个我想测试的对象的代码。 我在测试中使用了部分模拟,并且在测试GenerateReport方法时想要模拟对InsertData的调用。 出于某种原因,我的测试继续向下通过InsertData到DoSomeStuff并在Path.Combine行上失败。我错过了什么?

public class MyClass : IMyClass
{
    private readonly IMyClassDataProvider _myClassDataProvider;

    public virtual string WorkingDirectory { get; set; }

    public MyClass(IMyClassDataProvider myClassDataProvider)
    {
        _myClassDataProvider = myClassDataProvider;
    }

    internal virtual void ValidateWorkingDirectory()
    {
        if (string.IsNullOrEmpty(WorkingDirectory))
        {
            throw new ApplicationException("Must set Working Directory before any method calls.");
        }
    }

    public virtual void GenerateReport(vars)
    {
        ValidateWorkingDirectory();
        InsertData(_myClassDataProvider.GetData(vars), "ReportName"); 
                    //want to mock the call above
    }

    internal virtual void InsertData(DataSet analysis, string fileName)
    {
        DoSomeStuff();
    }

    private static void DoSomeStuff()
    {
        string fileName = FileNameProvider.Get();
        Path.Combine(WorkingDirectory, fileName); //fails here!
    }
}


[TestFixture]
public class MyClassTests : TestFixtureBase
{
    private MockRepository _mocks;
    private IMyClassDataProvider  _myClassDataProvider;
    private MyClass _myClass;
    private var _vars;

    [SetUp]
    protected void Init()
    {
        _mocks = new MockRepository();
        _myClassDataProvider = _mocks.StrictMock<IMyClassDataProvider >();
        _myClass = _mocks.PartialMock<MyClass>(_myClassDataProvider);
        _vars = "who cares";
    }

    [Test]
    public virtual void ShouldGenerateReport()
    {
        DataSet dataSetToReturn = new DataSet();
        using (_mocks.Ordered())
        {
            Expect.Call(() => _myClass.ValidateWorkingDirectory());
            Expect.Call(_myClassDataProvider.GetData(vars)).Return(dataSetToReturn);
            Expect.Call(() => _myClass.InsertData(dataSetToReturn, "ReportName"));
        }
        _mocks.ReplayAll();
        _myClass.GenerateReport(vars);
        _mocks.VerifyAll();
    }
}

1 个答案:

答案 0 :(得分:1)

将InsertData从内部更改为public将解决此问题。我假设一个方法需要公开,以便Rhino模拟能够模拟方法调用。

关于在期望之后添加IgnoreArguements,我不太确定它是如何通过的,因为当我尝试运行此代码时它仍然调用了orignal方法。

希望这有帮助