Skip to content

Instantly share code, notes, and snippets.

@marzoukali
Created July 9, 2017 21:23
Show Gist options
  • Save marzoukali/b44bb640f045e6b904d72e121e63c462 to your computer and use it in GitHub Desktop.
Save marzoukali/b44bb640f045e6b904d72e121e63c462 to your computer and use it in GitHub Desktop.
unittest-example-10
// This class will be used to create a simple GOF singletone object.
public class Security
{
private static Security _instance;
private string _userName;
private bool _isAdmin;
public static Security GetInstance()
{
if (_instance == null)
_instance = new Security();
return _instance;
}
private Security() { }
public void SetUser(string userName, bool isAdmin)
{
_userName = userName;
_isAdmin = isAdmin;
}
public string GetUserName()
{
return _userName;
}
public bool IsAdmin()
{
return _isAdmin;
}
}
// The issue shown here while we used GOF singleton object Security.GetInstance(); which will be hard to test.
public class PrintInvoiceCommand
{
private readonly IDatabase _database;
private readonly IInvoiceWriter _writer;
public PrintInvoiceCommand(
IDatabase database,
IInvoiceWriter writer)
{
_database = database;
_writer = writer;
}
public void Execute(int invoiceId)
{
var invoice = _database.GetInvoice(invoiceId);
var security = Security.GetInstance();
if (!security.IsAdmin())
throw new UserNotAuthorizedException();
_writer.Print(invoice);
invoice.LastPrintedBy = security.GetUserName();
_database.Save();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment