gpt4 book ai didi

c# - Rhino Mocks - 将 Expect.Call 用于具有两个签名的方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:40:16 25 4
gpt4 key购买 nike

如何模拟具有两个签名的方法?

须藤代码:

public Class ClassA{
//... do stuff
}

public Class ClassB{
//... do stuff
}

public Class BigClass
{
public BigClass(){}

public ClassB MapMe(ClassA a)
{
//... do stuff
return new ClassB();
}

public ClassA MapMe(ClassB a)
{
//... do stuff
return new ClassA();
}
}

public Class ClassToTest
{
public void DoSomething()
{
var ResultA = BigClass.MapMe(new ClassA());

//... do some more stuff

ResultA = BigClass.MapMe(new ClassB());
}
}

对于糟糕的代码示例,在 iPad 上执行此操作表示歉意,但希望能给您带来灵感。

最佳答案

只需使用 Argument Constraints

Argument constraints also define the method's signature by specifying the arguments types. That's why they can't be omitted.

mock.Expect(x => x.MapMe(Arg<ClassB>.Is.Anything).Return(resultB);
mock.Expect(x => x.MapMe(Arg<ClassA>.Is.Anything).Return(resultA);

编辑:

我相信您遇到了另一个问题 - 您在没有支持接口(interface)的情况下模拟了 BigClass,因此显然 RhinoMocks 不允许在这样的模拟上设置期望。所以只需通过接口(interface)抽象一个 BigClass 并基于它进行模拟:

public interface IMapper
{
ClassB MapMe(ClassA entity);
ClassA MapMe(ClassB entity);
}

public class BigClass : IMapper


[Test]
public void MapperTest()
{
// !!! Below I've used WhenCalled() to show you that correct
// expectation is called based on argument type, just see in debugger
IMapper mapperMock = MockRepository.GenerateMock<IMapper>();
mapperMock.Expect(x => x.MapMe(Arg<ClassA>.Is.Anything))
.WhenCalled((mi) =>
{
Debug.WriteLine("MapMe - ClassA parameter");
})
.Return(null /*TODO: return correct instance*/);
mapperMock.Expect(x => x.MapMe(Arg<ClassB>.Is.Anything))
.WhenCalled((mi) =>
{
Debug.WriteLine("MapMe - ClassB parameter");
})
.Return(null /*TODO: return correct instance*/);

var resultB = mapperMock.MapMe(new ClassA());
var resultA = mapperMock.MapMe(new ClassB());

// TODO: Asserts
}

关于c# - Rhino Mocks - 将 Expect.Call 用于具有两个签名的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9691930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com