4
votes

I have the following method signature that I would like to set up a mock:-

public int Update<T>(T item) where T : IItemID, IItemData

When trying to set up the mock (using Moq), I cannot set the correct type for T:-

mock.Setup(x => x.Update(It.IsAny<???>()).Returns(1);

I've tried with a "fake" interface in my unit test project:-

public interface IFake : IITemID, IItemData
{
}

mock.Setup(x => x.Update(It.IsAny<IFake>()).Returns(1)

but the verify in my unit test fails because the object I'm using does not inherit from IFake. The object is an actual type that inherits from IItemID and IItemData.

Is there anyway to set up the mock for this Update method with multiple constraints?

UPDATE Thanks for the info all. After going through this again it looks like the best solution is to not use multiple interface constraints as this can't be mocked. I just wondered if there was a solution to this as it seems like something that can cause massive problems later down the line.

Thanks again!

1
Does the Update() method appear in both interfaces? If not can't you just mock the appropriate interface required for the unit test? - AlwaysLearning
Show the test and the system under test - Nkosi
I think the easiest is to create a new interface IItem : IItemIdD, IItemData and use that as a constraint. It will be easier to mock. - Johnny
I second what Johnny said, make another interface and mock that. I think the fact that you're having trouble mocking it exposes some unrefined data design. You said your object doesn't inherit from IFake, but it should, or it should at least inherit from IItem as above. - Zakk Diaz

1 Answers

0
votes

Try

mock.Setup(x => x.Update(It.IsAny<It.IsAnyType>()).Returns(1);