【发布时间】:2019-11-15 12:37:30
【问题描述】:
我正在尝试为依赖于依赖项的方法编写单元测试,该依赖项提供了一种接受对象并修改它的方法,但不会在“新路径”上返回它,例如作为返回值或引用参数。
public class Product
{
public string Name { get; set; }
}
public interface IFixer
{
void Modify(Product product);
}
public class Fixer: IFixer
{
public void Modify(Product product)
{
if (string.IsNullOrEmpty(product.Name))
{
product.Name = "Default";
}
}
}
public class Manager()
{
private readonly IFixer _fixer;
public Manager(IFixer fixer)
{
_fixer = fixer;
}
public bool IsProductNew(int id)
{
var product = GetProduct(id); // Gets an object instance from a repository, e.g. a file or a database, so we can have something to operate on.
_fixer.Modify(product);
return product.Name != "Default";
}
}
所以我希望能够测试我的Manager 类'IsProductNew() 方法:
var fakeFixer = A.Fake<IFixer>();
var manager = new Manager(fakeFixer);
var isNew = manager.IsProductNew(A<int>._);
Assert.True(isNew);
我在这里缺少的是:如何模拟 IFixer.Modify() 的行为,即让它修改 Product 对象实例?
【问题讨论】:
-
什么是GetProduct(id);做?它是在哪里定义的?
-
它只是一个占位符,表示将有多种
Product对象实例可用,因此具有修改功能是有实际价值的。
标签: c# unit-testing fakeiteasy