jeudi 28 juillet 2016

How to mocking an IEnumerable

I got a class which looks like below

public interface ILocationProvider
{
    bool IsRequiredLocation (string type);
}

public class MyClass : IMyInterface
{
    private readonly IEnumerable<ILocationProvider> _locationProvider;
    public MyClass (ILocationProvider[] locationProvider)
    {
        _locationProvider = locationProvider;
    }
    public ILocationProvider ProvideRequireLocationObject(string type)
    {
        ILocationProvider location = _locationProvider.FirstOrDefault(x => x.IsRequiredLocation(type));
        return location;
    }
}

Now I am trying to write some tests for it. But I stuck passing the Mock<IEnumerable<ITransitReportCountryFlowProvider>> to constructor. Below my test code

[TestClass]
public class TMyClassTest
{
    private Mock<IEnumerable<ILocationProvider>> _locationProvider = null;
    private IMyInterface _myClass = null;
    [TestInitialize]
    public void InitializeTest ()
    {
        _locationProvider = new Mock<IEnumerable<ILocationProvider>>();
    }
    [TestMethod]
    public void ProvideRequireLocationObject_Test1()
    {
        //Given: I have type as 'PMI'
        string type = "PMI";
        //When: I call MyClass object
        _myClass = new MyClass(_locationProvider.Object); //wrong actual argument as the formal argument is an array of ILocationProvider
        //_locationProvider.Setup(x => x.IsRequiredCountryFlow(It.IsAny<string>())).Returns(true); //how do I setup
        ILocationProvider result = _myClass.ProvideRequireLocationObject(type);
        //Then: I get a type of ILocationProvider in return
        Assert.IsTrue(result is ILocationProvider);
    }
}

Problem 1: The line _myClass = new MyClass(_locationProvider.Object) in above test class, as the constructor's formal argument is ILocationProvider[] so I cannot pass a mocking object of Mock<IEnumerable<ILocationProvider>>

Problem 2: If I change the line private readonly IEnumerable<ILocationProvider> _locationProvider; in above MyClass to private readonly ILocationProvider[] _locationProvider; I will not be able to mock it as because mock must be an interface or an abstract or non-sealed class.

Problem 3: How do I set up for _locationProvider.FirstOrDefault(x => x.IsRequiredLocation(type)); in my test method

Problem 4: How do I assert that my method ProvideRequireLocationObject is returning a type of ILocationProvider

Aucun commentaire:

Enregistrer un commentaire