Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Last active September 4, 2018 21:15
Show Gist options
  • Save sangheestyle/aec73134f7abea3ae0e06147198d49d8 to your computer and use it in GitHub Desktop.
Save sangheestyle/aec73134f7abea3ae0e06147198d49d8 to your computer and use it in GitHub Desktop.
Say I want to mock out a framework class which doesn't implement an interface
using System;
public class ExchangeService
{
public void Subscribe()
{
Console.WriteLine("Exchange: Subscribe");
}
public void Unsubscribe()
{
Console.WriteLine("Exchange: Unsubscribe");
}
}
class SubscriptionHandlerA
{
private readonly ExchangeService _service;
public SubscriptionHandlerA(ExchangeService service)
{
_service = service;
}
public void Subscribe()
{
// do something more
_service.Subscribe();
// do something more
}
public void Unsubscribe()
{
// do something more
_service.Unsubscribe();
// do something more
}
}
public interface IExchangeServiceAdapter
{
void Subscribe();
void Unsubscribe();
}
public class ExchangeServiceAdapter: IExchangeServiceAdapter
{
private readonly ExchangeService _service;
public ExchangeServiceAdapter(ExchangeService service)
{
_service = service;
}
public void Subscribe()
{
_service.Subscribe();
}
public void Unsubscribe()
{
_service.Unsubscribe();
}
}
public class ExchangeServiceMock: IExchangeServiceAdapter
{
public void Subscribe()
{
Console.WriteLine("ExchangeServiceMock: Subscribe");
}
public void Unsubscribe()
{
Console.WriteLine("ExchangeServiceMock: Unsubscribe");
}
}
class SubscriptionHandlerB
{
private readonly IExchangeServiceAdapter _service;
public SubscriptionHandlerB(IExchangeServiceAdapter service)
{
_service = service;
}
public void Subscribe()
{
_service.Subscribe();
}
public void Unsubscribe()
{
_service.Unsubscribe();
}
}
class Program
{
static void Main(string[] args)
{
var handlerA = new SubscriptionHandlerA(new ExchangeService());
handlerA.Subscribe();
handlerA.Unsubscribe();
var handlerB = new SubscriptionHandlerB(
new ExchangeServiceAdapter(
new ExchangeService()));
handlerB.Subscribe();
handlerB.Unsubscribe();
var handlerBWithMock = new SubscriptionHandlerB(new ExchangeServiceMock());
handlerBWithMock.Subscribe();
handlerBWithMock.Unsubscribe();
}
}
@sangheestyle
Copy link
Author

sangheestyle commented Sep 4, 2018

I like the following part:

"Say I want to mock out a framework class which doesn't implement an interface (and doesn't have virtual methods). With many mocking apis this is hard or impossible to do. What I will do, then, is define my own interface as a subset of the signature of the class I'm targeting."

from https://stackoverflow.com/questions/1299167/understanding-adapter-pattern

Also I like the following:

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