[英]How to use class Object in out parameter with Moq
我试图模拟我的服务的一些功能。 代码是这样的。
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
方法行为 vai 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);
但它抛出此错误->“属性或索引器可能不会作为 out 或 ref 参数传递”
试试“mockIObj.Object”。 这应该传入模拟对象而不是模拟实例
我找到了解决此问题的其他方法。 这个方法public bool SomeMethod(string input, out IObj outputObj)
正在调用另一个方法,比如这个public bool oneAnotherMethod(string input, out string outputResponse)
这个方法解决了这个问题。
我不知道模拟内部调用可以在调用链之上传播。
感谢所有的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.