我被要求将一个非常老的代码库升级到.net 6,升级后单元测试不再通过,因为模拟库NMock2不支持.net 6。我尝试用.net 6替换旧的模拟库,但遇到了新的问题。由于我不是任何一个图书馆的专家,有人能帮我升级吗?
Expect.Exactly(3).On(aHandlerMock).Method("APublicMethod").WithAnyArguments()和Expect.Exactly(2).On(aHandlerMock).GetProperty("AOnlyGetterAvailableProperty").Will(Return.Value(false))的等效词是什么?
问题的详情:
包含NMock2的测试类如下所示:
[SetUp]
public void SetUp()
{
this.mockery = new Mockery();
this.messageDelegatorMock = this.mockery.NewMock<IDispatcher>();
this.xHandlerFactoryMock = this.mockery.NewMock<IXHandlerFactory>();
this.xHandlerMock = this.mockery.NewMock<IXHandler>();
this.incomingXDelegate = new IncomingXDelegate(this.messageDelegatorMock)
{
XHandlerFactory = this.xHandlerFactoryMock
};
}
[Test]
public void TestHandleXSimple()
{
TestX testX = new TestX(new Collection<string>());
CY y1 = new CY("1", 0, false);
CY y2 = new CY("1", 1, false);
CY y3 = new CY("1", 2, true);
Expect.Once.On(this.xHandlerFactoryMock)
.Method("createXHandler")
.With(typeof(TestX), "1")
.Will(Return.Value(this.xHandlerMock));
Expect.Exactly(3).On(this.xHandlerMock)
.Method("addMessage")
.WithAnyArguments();
Expect.Exactly(2).On(this.xHandlerMock)
.GetProperty("IsComplete")
.Will(Return.Value(false));
Expect.Once.On(this.xHandlerMock)
.GetProperty("IsComplete")
.Will(Return.Value(true));
Expect.Once.On(this.XHandlerMock)
.GetProperty("Message")
.Will(Return.Value(testX));
Expect.Once.On(this.messageDelegatorMock).Method("Dispatch");
incomingXDelegate.OnX(testX, y1);
incomingXDelegate.OnX(testX, y2);
incomingXDelegate.OnX(testX, y3);
mockery.VerifyAllExpectationsHaveBeenMet();
}addMessage(object message, IMh info)在IXHandler中声明,在测试夹具中,类CY实现IMh。
我的问题是:如何在示例中使用Moq来模拟NMock2的行为?非常感谢您的慷慨帮助!
发布于 2022-07-05 09:41:05
我对NMock2没有任何经验,但这段代码在它所期望的方面似乎相当明确。
在此基础上,并假设所测试的类如下所示:
public interface IXHandlerFactory
{
void APublicMethod(int argOne, int argTwo);
bool AOnlyGetterAvailableProperty { get; }
}Expect.Exactly(3).On(aHandlerMock).Method("APublicMethod").WithAnyArguments()
会像这样:
//Create the mock and call the method as an example
var mock = new Mock<IXHandlerFactory>();
mock.APublicMethod(1, 2);
//Verify the method was called the expected number of times with any value
//for the arguments
mock.Verify(x => x.APublicMethod(It.IsAny<int>(), It.IsAny<int>()), Times.Exactly(3));Moq中的Times类有许多有用的方法来指定调用预期方法的频率(如果有的话)。如果期望不匹配,就会抛出一个异常,该异常通常会在我过去使用过的框架中失败。
同样,It类上也有许多方法,比如Any (也就是说,我不在乎值是什么),或者如果您想要更具体一些,可以在Is中插入一个自定义比较。
Expect.Exactly(2).On(aHandlerMock).GetProperty("AOnlyGetterAvailableProperty").Will(Return.Value(false))
会像这样:
//Create the mock as before
var mock = new Mock<IXHandlerFactory>();
//Any calls to AOnlyGetterAvailableProperty will return false
mock.Setup(x => x.AOnlyGetterAvailableProperty).Returns(false);
//Run the test
//Assert the expectation
mock.Verify(x => x.AOnlyGetterAvailableProperty, Times.Exactly(2));https://stackoverflow.com/questions/72862261
复制相似问题