我试图模拟我的服务的一些功能。代码如下:
public interface IObj {
public bool anotherMethod(string input, out string responseString);
}
public class SomeClass {
public bool SomeMethod(string input, out IObj outputObj) {
// some logic
if (logic is correct) {
outputObj = // object of IObj
return true;
}
outputObj = null;
return false;
}
}
public class Service {
public void executingMethod(){
if (this.someClassObj.SomeMethod(this.inputString, out outputObj) {
if (outputObj.anotherMethod(this.anotherInputString, out responseString)
{
// some business logic
}
}
}
}
现在我想用Moq和xUnit模拟方法executingMethod
行为值UnitTest。但在嘲笑我得到out
参数的问题。通过这种方式,我试图嘲笑这种行为。
[Fact]
public void MockingMethod(){
// Arrange
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
Mock<IObj> mockIObj = new Mock<IObj>();
string mockedResponse = "someResponse";
// here i am getting the issue, as out is expecting actual object not mocked object.
mockSomeClass.Setup(s => s.SomeMethod(It.IsAny<string>(), out mockIObj).Returns(true);
mockIObj.Setup(s => s.anotherMethod(It.IsAny<string(), out mockedResponse).Returns(true);
}
任何帮助都将非常感激。TIA。
我也试着按照@Roman的建议使用。mockSomeClass.Setup(s => s.SomeMethod(It.IsAny<string>(), out mockIObj.Object).Returns(true);
但是它抛出了这个错误->属性或索引不能作为输出或引用参数传递
尝试" mockIObj. "对象"。这应该传入模拟对象而不是模拟实例
我找到了解决这个问题的其他方法。此方法public bool SomeMethod(string input, out IObj outputObj)
正在调用像这样的另一个方法public bool oneAnotherMethod(string input, out string outputResponse)
嘲弄这个方法解决这个问题。
我不知道模拟内部调用可以在调用链上传播。
谢谢你的帮助。