使用Rhino Mocks,如何拦截对接口上单个属性的调用,同时将其他所有内容传递给“默认实现”?

发布于 2024-10-02 00:14:21 字数 148 浏览 2 评论 0原文

我有一个带有许多方法和属性的接口 IComplex,我希望创建一个“模拟”,使“Config”属性返回我选择的对象,同时将所有其他调用传递给“真实” IComplex 的实例。

只是为了让这个变得更难一点,我们仍然使用 C# V2!

I have an interface IComplex with many methods and properties, I wish to create a “mock” that makes the “Config” property return an object of my choose, while passing all other calls onto a “real” instance of IComplex.

Just to make this a bit harder we are still using C# V2!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

亚希 2024-10-09 00:14:22

您想要创建一个代理对象,它将所有调用传递到实际实现的实例 - 除非您想要覆盖成员的行为。

据我所知,Rhino Mocks 不支持这一点。但是,您也许可以使用 Castle 动态代理 自己构建类似的模拟功能图书馆。 (Rhino 模拟使用相同的库。)

You want to create a proxy object which passes all calls through to an instance of the real implementation - except when you want to override behavior of a member.

As far as I know, Rhino Mocks does not support this. However, you might be able to build a mocking feature like that yourself with the Castle Dynamic Proxy library. (Rhino mocks uses the same library.)

旧情勿念 2024-10-09 00:14:21

据我所知,没有一个功能可以同时配置多个mock方法。您需要指定所有方法以将它们转发到其他实现......

除非您编写一些反射代码来配置模拟。

这是一些(工作)代码。它使用 C# 3.0,但主要部分是为 C# 2.0 编写的“旧式”Rhino Mocks 内容。

public static class MockExtensions
{

    public static void ForwardCalls<T>(this T mock, T original)
    {
        mock.BackToRecord();
        Type mockType = typeof(T);
        var methods = mockType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
            .Union(mockType.GetInterfaces().SelectMany(x => x.GetMethods(BindingFlags.Public | BindingFlags.Instance)));
        foreach (MethodInfo method in methods)
        {
            List<object> args = new List<object>();
            foreach (var arg in method.GetParameters())
            {
                args.Add(CreateDefaultValue(arg.ParameterType));
            }
            method.Invoke(mock, args.ToArray());
            var myMethod = method;
            if (method.ReturnType == typeof(void))
            {
                LastCall
                    .IgnoreArguments()
                    // not Repeat.Any to allow overriding the value
                    .Repeat.Times(int.MaxValue)
                    .WhenCalled(call => myMethod.Invoke(original, call.Arguments));
            }
            else
            {
                LastCall
                    .IgnoreArguments()
                    // not Repeat.Any to allow overriding the value
                    .Repeat.Times(int.MaxValue)
                    .WhenCalled(call => call.ReturnValue = myMethod.Invoke(original, call.Arguments))
                    .Return(CreateDefaultValue(myMethod.ReturnType));
            }
        }
        mock.Replay();
    }

    private static object CreateDefaultValue(Type type)
    {

        if (type.IsValueType)
        {
            return Activator.CreateInstance(type);
        }
        else
        {
            return Convert.ChangeType(null, type);
        }
    }

}

用法:

[TestClass]
public class TestClass()
{
    [TestMethod]
    public void Test()
    {
        var mock = MockRepository.GenerateMock<IList<int>>();
        List<int> original = new List<int>();

        mock.ForwardCalls(original);

        mock.Add(7);
        mock.Add(8);
        Assert.AreEqual(2, mock.Count);
        Assert.AreEqual(7, mock[0]);
        Assert.AreEqual(8, mock[1]);

        //fake Count after ForwardCalls, use Repeat.Any()
        mock.Stub(x => x.Count)
            .Return(88)
            .Repeat.Any(); // repeat any needed to "override" value

        // faked count
        Assert.AreEqual(88, mock.Count);
    }
}

As far as I know, there isn't a feature to configure many methods of mock at once. You need to specify all the methods to forward them to the other implementation...

... unless you write some reflection code to configure the mock.

Here is some (working) code. It uses C# 3.0, but the main part is "old style" Rhino Mocks stuff which had been written for C# 2.0.

public static class MockExtensions
{

    public static void ForwardCalls<T>(this T mock, T original)
    {
        mock.BackToRecord();
        Type mockType = typeof(T);
        var methods = mockType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
            .Union(mockType.GetInterfaces().SelectMany(x => x.GetMethods(BindingFlags.Public | BindingFlags.Instance)));
        foreach (MethodInfo method in methods)
        {
            List<object> args = new List<object>();
            foreach (var arg in method.GetParameters())
            {
                args.Add(CreateDefaultValue(arg.ParameterType));
            }
            method.Invoke(mock, args.ToArray());
            var myMethod = method;
            if (method.ReturnType == typeof(void))
            {
                LastCall
                    .IgnoreArguments()
                    // not Repeat.Any to allow overriding the value
                    .Repeat.Times(int.MaxValue)
                    .WhenCalled(call => myMethod.Invoke(original, call.Arguments));
            }
            else
            {
                LastCall
                    .IgnoreArguments()
                    // not Repeat.Any to allow overriding the value
                    .Repeat.Times(int.MaxValue)
                    .WhenCalled(call => call.ReturnValue = myMethod.Invoke(original, call.Arguments))
                    .Return(CreateDefaultValue(myMethod.ReturnType));
            }
        }
        mock.Replay();
    }

    private static object CreateDefaultValue(Type type)
    {

        if (type.IsValueType)
        {
            return Activator.CreateInstance(type);
        }
        else
        {
            return Convert.ChangeType(null, type);
        }
    }

}

Usage:

[TestClass]
public class TestClass()
{
    [TestMethod]
    public void Test()
    {
        var mock = MockRepository.GenerateMock<IList<int>>();
        List<int> original = new List<int>();

        mock.ForwardCalls(original);

        mock.Add(7);
        mock.Add(8);
        Assert.AreEqual(2, mock.Count);
        Assert.AreEqual(7, mock[0]);
        Assert.AreEqual(8, mock[1]);

        //fake Count after ForwardCalls, use Repeat.Any()
        mock.Stub(x => x.Count)
            .Return(88)
            .Repeat.Any(); // repeat any needed to "override" value

        // faked count
        Assert.AreEqual(88, mock.Count);
    }
}
早茶月光 2024-10-09 00:14:21

您可以使用PartialMock方法创建模拟。

您将真实类的类型传递给此方法,并且仅注册需要模拟的调用。

请注意,您想要模拟 IComplex 实现的方法必须是虚拟的才能完成此操作。

请参阅http://www.ayende.com/wiki/Rhino+Mocks+ Partial+Mocks.ashx 了解更多信息。

You can use the PartialMock method to create a mock.

You pass the type of the real class to this method and only register the calls that you need to mock.

Note that the methods you want to mock of the IComplex implementation need to be virtual to accomplish this.

See http://www.ayende.com/wiki/Rhino+Mocks+Partial+Mocks.ashx for more information.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文