C# 如何在单元测试项目中创建新对象?

C# 如何在单元测试项目中创建新对象?,c#,unit-testing,asp.net-core,C#,Unit Testing,Asp.net Core,我有一个使用接口的类。我想在单元测试中使用类本身,但我不知道如何做 我的代码: public class Store { private readonly ICache _Cache; public CacheStore(ICache cache) { _Cache= cache; } } 现在如何使用CacheStore类 [Test] public void test_method() { var options = new Cac

我有一个使用接口的类。我想在单元测试中使用类本身,但我不知道如何做

我的代码:

public class Store
{
    private readonly ICache _Cache;
    public CacheStore(ICache cache)
    {
        _Cache= cache;
    } 
}
现在如何使用CacheStore类

[Test]
public void test_method()
{
    var options = new CacheStore(??);
}

您需要模拟ICache接口

假设您有这样定义的store类

public class Store
{
    private readonly ICache _Cache;

    public Store(ICache cache)
    {
         _Cache = cache;
    }
}
在单元测试中,必须创建
ICache

Mock<ICache> _icache = new Mock<ICache>();
之后,您可以使用Moq的设置方法设置必填字段。
如果您是新的模拟,请参考以下内容。

您将需要模拟
ICache的测试实现。
您实际想做什么?这可能是一个。两种选择:-使用moking库作为Moq或在测试项目中实现存根(一个实现ICache的假类)
Store _s = new Store(_icache.Object);