gpt4 book ai didi

unit-testing - 未在模拟上执行 Moq 调用

转载 作者:行者123 更新时间:2023-12-04 16:50:06 25 4
gpt4 key购买 nike

试图了解 verifySet 等的使用......但除非我采取解决方法,否则我无法让它工作。

public interface IProduct
{
int Id { get; set; }
string Name { get; set; }
}


public void Can_do_something()
{
var newProduct = new Mock<IProduct>();
newProduct.SetupGet(p => p.Id).Returns(1);
newProduct.SetupGet(p => p.Name).Returns("Jo");

//This fails!! why is it because I have not invoked it
newProduct.VerifySet(p => p.Name, Times.AtLeastOnce());

//if I do this it works
newProduct.Object.Name = "Jo";
newProduct.VerifySet(p => p.Name, Times.AtLeastOnce());
}

有人可以澄清我应该如何在属性上使用 VerifySet 和 Verify 和 VerifyGet 吗?
我越来越糊涂了。

最佳答案

您需要在调用验证之前执行操作。模拟对象的典型单元测试范式是:

// Arrange
// Act
// Assert

因此,以下是不正确的用法,因为您缺少 Act 步骤:
public void Can_do_something()
{
// Arrange
var newProduct = new Mock<IProduct>();
newProduct.SetupGet(p => p.Name).Returns("Jo");

// Act - doesn't exist!
// Your action against p.Name (ie method call), should occur here

// Assert
// This fails because p.Name has not had an action performed against it
newProduct.VerifySet(p => p.Name, Times.AtLeastOnce());
}

这是正确的,因为法案存在:
public void Can_do_something()
{
// Arrange
var newProduct = new Mock<IProduct>();
newProduct.SetupGet(p => p.Name).Returns("Jo");

// Act
LoadProduct(newProduct.Object);

// Assert
newProduct.VerifySet(p => p.Name, Times.AtLeastOnce());
}

public static void LoadProduct(IProduct product)
{
product.Name = "Jo";
}

模拟测试遵循与非模拟测试不同的模式,称为 行为验证 - 这是我制作的 answer ,它将进一步阐明这个概念。

关于unit-testing - 未在模拟上执行 Moq 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1179757/

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