gpt4 book ai didi

c#单元测试子方法调用参数

转载 作者:行者123 更新时间:2023-11-30 21:27:40 26 4
gpt4 key购买 nike

这是我的 c# 代码。

我不确定应该如何验证使用正确参数调用的 Get 方法。

public class ClassToTest
{
public IList<Products> GetProducts(string categoryId)
{
var items = _service.Get(new Category { id = categoryId, flag = true });
return items;
}
}

例如它是用 Category 类对象调用的,参数 flagtrueid 为传递。

最佳答案

使用FakeItEasy 和依赖倒置原理,就这么简单:

你的类(class)略有变化:

public class ClassToTest
{
private readonly IService _service;

public ClassToTest(IService service) =>
_service = service;

public IList<Products> GetProducts(string categoryId) =>
_service.Get(new Category { id = categoryId, flag = true });
}

public interface IService
{
IList<Products> Get(Category category);
}

测试:

[Test]
public void Test()
{
// Arrange
string categoryId = "categoryId";
IService service = A.Fake<IService>();
ClassToTest sut = new ClassToTest(service);

// Act
sut.GetProducts(categoryId);

// Assert
A.CallTo(() => service.Get(A<Category>.That.Matches(i => i.id == categoryId && i.flag)))
.MustHaveHappened();
}

[Test]
public void Test()
{
// Arrange
string actualId = null;
bool? actualFlag = null;

string categoryId = "categoryId";
IService service = A.Fake<IService>();
A.CallTo(() => service.Get(A<Category>.Ignored)).Invokes((Category category) =>
{
actualId = category.id;
actualFlag = category.flag;
});

ClassToTest sut = new ClassToTest(service);

// Act
sut.GetProducts(categoryId);

// Assert
Assert.AreEqual(categoryId, actualId);
Assert.AreEqual(true, actualFlag);
// optionaly, because it obviously happened
A.CallTo(() => service.Get(A<Category>.Ignored))
.MustHaveHappened();
}

关于c#单元测试子方法调用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398950/

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