编程语言
首页 > 编程语言> > c#-使用RhinoMocks .NET进行简单模拟的麻烦

c#-使用RhinoMocks .NET进行简单模拟的麻烦

作者:互联网

我正在尝试使用RhinoMocks进行实验,在这里我不得不说我是一个新手,而且我可能在这里看不到任何明显的东西.我在做什么就像:

    [TestMethod]
    public void SaveResponsibleUserFromChangeset()
    {
        var action = mocks.StrictMock<GenomeAction>();
        var changeset = new ActionChangeset();

        changeset.ResponsibleUser = new ChangeableProperty<UserIdentity>("Administrator") {IsChanged = true};
        changeset.MarkAll(true);

        using(mocks.Record())
        {
            Expect.Call(action.ResponsibleUser).SetPropertyAndIgnoreArgument();
        }

        using(mocks.Playback())
        {
            var persistor = new ActionPersistor(new MockIdentityResolver());
            persistor.SaveActionChanges(changeset, action);
        }

        action.VerifyAllExpectations();
    }

    private class MockIdentityResolver : IIdentityResolver
    {
        public GenomeUser GetUser(UserIdentity identity)
        {
            var user = mocks.DynamicMock<GenomeUser>();
            user.Username = identity.Username;
            return user;
        }
    }

目的是进行一个非常简单的测试,该测试检查SaveActionChanges方法是否设置了ResponsibleUser属性.作为其一部分,它需要使用解析器解析用户身份,为此我提供了一个模拟实现.不幸的是,似乎我不能在Playback模式下返回另一个模拟,因为它说(在第二个使用的结尾),当对象(GenomeUser类型)处于记录状态时,该动作无效.

关于造成麻烦的原因以及如何解决的任何想法?

解决方法:

我认为您需要在嘲笑()之外创建新的MockIdentityResolver().

[TestMethod]
public void SaveResponsibleUserFromChangeset()
{
    var action = mocks.StrictMock<GenomeAction>();
    var changeset = new ActionChangeset();
    var identityResolver;
    changeset.ResponsibleUser = new ChangeableProperty<UserIdentity>("Administrator") {IsChanged = true};
    changeset.MarkAll(true);

    using(mocks.Record())
    {
        Expect.Call(action.ResponsibleUser).SetPropertyAndIgnoreArgument();
        identityResolver = new MockIdentityResolver()
    }

    using(mocks.Playback())
    {
        var persistor = new ActionPersistor(identityResolver);
        persistor.SaveActionChanges(changeset, action);
    }

    action.VerifyAllExpectations();
}

private class MockIdentityResolver : IIdentityResolver
{
    public GenomeUser GetUser(UserIdentity identity)
    {
        var user = mocks.DynamicMock<GenomeUser>();
        user.Username = identity.Username;
        return user;
    }
}

您应该看一下使用AAA syntax的方法,似乎人们普遍认为这是使用材料的一种更清晰的方法.

标签:unit-testing,mocking,c,net,rhino-mocks
来源: https://codeday.me/bug/20191106/2001446.html