public
Last active

Simplify testing of proxy/decorator with generics in c#

  • Download Gist
ProxyTest.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
public class ProxyTest
{
public static void AssertProxyDelegation<T,U>(T proxy, Mock<T> proxiedMock, Expression<Func<T,U>> func, U retVal) where T : class
{
proxiedMock.Setup(func).Returns(retVal);
Assert.That(func.Compile().Invoke(proxy), Is.SameAs(retVal));
}
 
public static void AssertProxyDelegation<T>(T delegator, Mock<T> delegatedTo, Expression<Action<T>> action) where T : class
{
delegatedTo.Setup(action).Verifiable();
action.Compile().Invoke(delegator);
delegatedTo.Verify();
}
}
 
//example usage:
 
[TestFixture]
public class ProxyServiceTests
{
[Test]
public void CallProxied()
{
var proxiedMock = new Mock<Service>();
var proxy = Proxy.GetInstance(proxiedMock.Object);
ProxyTest.AssertProxyDelegation(proxy, proxiedMock, s=>s.DoSomething());
}
}
 
public abstract class Service
{
public abstract void DoSomething();
}
 
public class Proxy : Service
{
private readonly Service toProxy_;
 
private Proxy(Service toProxy)
{
toProxy_ = toProxy;
}
 
public static Service GetInstance(Service toProxy)
{
return new Proxy(toProxy);
}
 
public override void DoSomething()
{
toProxy_.DoSomething();
}
}

T delagator is misspelled

Thanks Steve, I finally saw this comment.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.