David
David

Reputation: 35

How to create a new object in the unit tests project?

I have a class that uses interface. I would like to use the class itself in my unit test, but I don't know how to do it.

My code:

public class Store
{
    private readonly ICache _Cache;
    public CacheStore(ICache cache)
    {
        _Cache= cache;
    } 
}

How to use the CacheStore class now?

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

Upvotes: 0

Views: 526

Answers (1)

Praveen M
Praveen M

Reputation: 453

You need to mock your ICache interface.

Say if you have store class is defined like this

public class Store
{
    private readonly ICache _Cache;

    public Store(ICache cache)
    {
         _Cache = cache;
    }
}

In your Unit Test, you have to create a Moq object of ICache

Mock<ICache> _icache = new Mock<ICache>();

You can create Store object using Moq object:

Store _s = new Store(_icache.Object);

After that, you can setup required fields using SetUp method of Moq. If you are new Mocking, please refer to the following link.

Upvotes: 1

Related Questions