I have a factory class returning a delegate like below (GetDelegate method)
public interface IFactory
{
Func<int, string> GetDelegate(bool isValid);
}
public class AFactory : IFactory
{
private readonly IService1 _service1;
private readonly IService2 _service2;
public AFactory(IService1 service1, IService2 service2)
{
_service1 = service1;
_service2= service2;
}
public Func<int, string> GetDelegate(bool isValid)
{
if (isValid)
return _service1.A;
return _service2.B;
}
}
public interface IService1
{
string A(int id);
}
public interface IService2
{
string B(int id);
}
I have been trying to write unit test for GetDelegate but dont know how to assert that a specific Func was returned depending on isValid
My attempt of a unit test is like below (which i am not happy with)
[Test]
public void ShouldReturnCorrectMethod()
{
private var _sut = new AFactory(new Mock<IService1>(), new Mock<IService2>());
var delegateObj = _sut.GetDelegate(true);
Assert.AreEqual(typeof(string), delegateObj.Method.ReturnType);
Assert.AreEqual(1, delegateObj.Method.GetParameters().Count());
}
Any help is much appreciated
thanks
One way would be to mock the result of calling IService1.A
and IService2.B
, in exactly the same way as if you were calling them directly. You could then check that when you call the returned delegate, you get the expected answer (and that the call was made to the appropriate service).
See more on this question at Stackoverflow