Skip to content

Instantly share code, notes, and snippets.

@marzoukali
Created July 3, 2017 10:55
Show Gist options
  • Save marzoukali/d6eec0896b9a07b14dfab79f581ed265 to your computer and use it in GitHub Desktop.
Save marzoukali/d6eec0896b9a07b14dfab79f581ed265 to your computer and use it in GitHub Desktop.
unittest-example-7
// The Code which have issues before refactoring
// First: issue is passing the whole container which known as service locator pattern (Anti-Pattern) because it will
// let us lost the value of mocking the real dependencies that the class is depend on and also the Auto Moqing with a tool like AutoMoqer
// will be no longer available.
// Second: There is an issue in LastPrintedBy as been shown below we violating the the law of demeter by calling object that we depend on
// then from it we call another object then another which made the testing difficult specially if those classes has no interface to implement which
// may let us swap the real objects with mocks easly.
public class PrintInvoiceCommand
{
private readonly Container _container;
// Issue 1
public PrintInvoiceCommand(
Container container)
{
_container = container;
}
public void Execute(int invoiceId)
{
var invoice = _container
.Get<IDatabase>()
.GetInvoice(invoiceId);
_container.Get<IInvoiceWriter>()
.Write(invoice);
// Issue 2
invoice.LastPrintedBy = _container
.Get<ISession>()
.GetLogin()
.GetUser()
.GetUserName();
_container
.Get<IDatabase>()
.Save();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment