DotCover显示虚拟方法模拟的0%

时间:2013-04-15 11:00:46

标签: c# unit-testing mocking

我正在使用DotCover检查单元测试覆盖率。在其中一个方法中,我从SearchResult中的活动目录返回结果但是,我模拟了该类,但DotCover显示0%

public virtual T SearchOneRecord(ISearchConfigurator configurator)
    {
        var record = (T)Activator.CreateInstance(typeof(T));
        var searchResult = configurator.DirectorySearcher.FindOne();
        if (searchResult != null)
        {
            AssignActiveDirectoryValue(searchResult, record);
        }

        return record;
    }

[Test]
    public void SearchOneRecord()
    {
        //Arrange
        var configuratorMock = MockRepository.GenerateMock<ISearchConfigurator>();
        var searchMock = MockRepository.GenerateStub<Searcher<NativeDs>>();
        searchMock.Replay();

        var nativeDs = new NativeDs() { PasswordAge = 100 };
        searchMock.Expect(x => x.SearchOneRecord(configuratorMock)).Return(nativeDs);

        //Act
        var record = searchMock.SearchOneRecord(configuratorMock);

        //Assert
        Assert.AreEqual(nativeDs.PasswordAge, record.PasswordAge);
    }

测试通过,但由于我是RhinoMock的新手(总体上是嘲笑),可能会有问题。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果我错了,请纠正我但你在这里做的是定义模拟然后测试这个模拟是否正常工作?我认为这不是你想要实现的。当然它会导致测试通过 - 模拟工作正常,但它根本不测试应用程序代码 - 因此0%覆盖率。

你想要做的可能是模拟ISearchConfigurator实例,然后将该模拟作为参数传递给方法。

[Test]
public void SearchOneRecord()
{
    //Arrange
    var configuratorMock = MockRepository.GenerateMock<ISearchConfigurator>();
    var directorySearcherMock = MockRepository.GenerateMock<IDirectorySearcher>(); // please note I don't know exact type, so you need to ammend it
    var returnValue = ... // initialize with types you expect DirectorySearcher to return
    var searcher = new Searcher(); // initialize class you actually want to test
    configurationMock.Replay();

    configurationMock.Expect(x => x.DirectorySearcher).Return(directorySearcherMock);
    directorySearcher.Expect(x => x.FindOne()).Return(returnValue);
    searchMock.Expect(x => x.SearchOneRecord(configuratorMock)).Return(nativeDs);

    //Act
    var record = searcher.SearchOneRecord(configuratorMock);

    //Assert
    Assert.AreEqual(nativeDs.PasswordAge, record.PasswordAge);
}

请注意,我目前无法测试此代码,但它应该为您提供一些指导方式。