mercredi 29 juillet 2015

Mocking an array exposed as a property

I've been given some code with this general structure:

public class A
{
    int Foo{ get; set; }
    byte Bar { get; set; }
}

public class B
{
    A[] _Baz = new A[10];

    A[] Baz
    {
        get { return _Baz; }
        set { _Baz = value; }
    }
}

I know, I know exposing an array, not great but it's what I've been give to work with.

Anyhow I'm looking to mock class B and set some of the array elements to specific values to be used by the consuming code.

It would seem that moq isn't able to do this directly but I have seen suggestions to mock an array of class A and return that via the class B mock. Kind of Like this:

var mockAArray = new Mock<A>[10];
mockAArray[3] = new Mock<B>();

var mockB = new Mock<B>();
mockB.Setup(x => x.A).Returns(mockAArray);

I say kind of because that doesn't actually work, I know I should be trying to return something like mockAArray.Object but I can't quite find the correct syntax to get this working.

Ultimately I'd like to refactor the code to get rid of the exposed array but I'd also like to get this test in place to help catch any breakages along the way

Aucun commentaire:

Enregistrer un commentaire