模拟(使用最小起订量)返回模拟对象的方法的正确方法?
以下哪一个是正确的?
var mockLogger = new Mock<EntLibLogger>();
mockLogger.Setup(i => i.CreateTracer(It.IsAny<string>()))
.Returns((string operationName) =>
{
var mockTracer = new Mock<EntLibTracer>(operationName);
mockTracer.Setup(i => i.IsTracingEnabled())
.Returns(true);
mockTracer.CallBase = true;
return mockTracer.Object;
});
mockLogger.CallBase = true;
//EntLibLogger.Current is a singleton that is shared across multiple threads.
//This Initialize method will set EntLibLogger.Current to the mocked instance
//instead of the default (non-mocked) configuration
EntLibLogger.Initialize(mockLogger.Object);
或者
var mockTracer = new Mock<EntLibTracer>(operationName);
mockTracer.Setup(i => i.IsTracingEnabled())
.Returns(true);
mockTracer.CallBase = true;
var mockLogger = new Mock<EntLibLogger>();
mockLogger.Setup(i => i.CreateTracer(It.IsAny<string>()))
.Returns(mockTracer.Object);
mockLogger.CallBase = true;
EntLibLogger.Initialize(mockLogger.Object);
我相信第一种方法是正确的,但我不确定 Moq 是否可能在幕后做一些魔法,只是想验证:)
Which of these is correct?
var mockLogger = new Mock<EntLibLogger>();
mockLogger.Setup(i => i.CreateTracer(It.IsAny<string>()))
.Returns((string operationName) =>
{
var mockTracer = new Mock<EntLibTracer>(operationName);
mockTracer.Setup(i => i.IsTracingEnabled())
.Returns(true);
mockTracer.CallBase = true;
return mockTracer.Object;
});
mockLogger.CallBase = true;
//EntLibLogger.Current is a singleton that is shared across multiple threads.
//This Initialize method will set EntLibLogger.Current to the mocked instance
//instead of the default (non-mocked) configuration
EntLibLogger.Initialize(mockLogger.Object);
OR
var mockTracer = new Mock<EntLibTracer>(operationName);
mockTracer.Setup(i => i.IsTracingEnabled())
.Returns(true);
mockTracer.CallBase = true;
var mockLogger = new Mock<EntLibLogger>();
mockLogger.Setup(i => i.CreateTracer(It.IsAny<string>()))
.Returns(mockTracer.Object);
mockLogger.CallBase = true;
EntLibLogger.Initialize(mockLogger.Object);
I believe the first approach is correct but I am not sure if Moq might be doing some magic under the hood and just wanted to validate :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想主要问题是如果它调用 CreateTracer 两次你想要发生什么。 在第一个版本中,您将获得两个不同的模拟跟踪器; 第二次你会得到同样的两次。
第二个版本是我通常在 jMock、EasyMock 和 Rhino.Mocks 中使用的版本 - 但我没有任何使用 Moq 的经验,因此使用第一个版本可能更惯用。 不过,第二个更简单,IMO:)
I guess the main question is what you want to happen if it calls
CreateTracer
twice. In the first version you'll get two different mock tracers; in the second you'll get the same one twice.The second version is what I've usually used in jMock, EasyMock and Rhino.Mocks - but I don't have any experience with Moq, so it may be more idiomatic to use the first form there. The second is simpler though, IMO :)