Skip to content

Instantly share code, notes, and snippets.

@tallseth
Last active October 12, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tallseth/4039017 to your computer and use it in GitHub Desktop.
Save tallseth/4039017 to your computer and use it in GitHub Desktop.
Simplify testing of proxy/decorator with generics in c#
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();
}
}
@steveburkett
Copy link

T delagator is misspelled

@tallseth
Copy link
Author

Thanks Steve, I finally saw this comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment