Skip to content

Instantly share code, notes, and snippets.

@marzoukali
Created July 9, 2017 21:28
Show Gist options
  • Save marzoukali/fe1ca00530d508819f86e38bfd359428 to your computer and use it in GitHub Desktop.
Save marzoukali/fe1ca00530d508819f86e38bfd359428 to your computer and use it in GitHub Desktop.
unittest-example-10
// The solution is to refactor the GOF class to be instance class and let it use interface to make it easy to inject
// Then use the IOC/DI singleton way to ensue using only one instance of the object.
// The Interface
public interface ISecurity
{
string GetUserName();
bool IsAdmin();
}
// Security class after refactoring to be instance class
public class Security : ISecurity
{
private string _userName;
private bool _isAdmin;
public void SetUser(string userName, bool isAdmin)
{
_userName = userName;
_isAdmin = isAdmin;
}
public string GetUserName()
{
return _userName;
}
public bool IsAdmin()
{
return _isAdmin;
}
}
// Use the Security class in the service class we want to test:
public class PrintInvoiceCommand
{
private readonly IDatabase _database;
private readonly ISecurity _security;
private readonly IInvoiceWriter _writer;
public PrintInvoiceCommand(
IDatabase database,
ISecurity security,
IInvoiceWriter writer)
{
_database = database;
_security = security;
_writer = writer;
}
public void Execute(int invoiceId)
{
var invoice = _database.GetInvoice(invoiceId);
if (!_security.IsAdmin())
throw new UserNotAuthorizedException();
_writer.Print(invoice);
invoice.LastPrintedBy = _security.GetUserName();
_database.Save();
}
}
// Ensure DI Singleton for the security class:
public class Program
{
static void Main(string[] args)
{
var invoiceId = int.Parse(args[0]);
var container = new StandardKernel();
container.Bind(p =>
{
p.FromThisAssembly()
.SelectAllClasses()
.BindDefaultInterface();
});
container.Bind<ISecurity>()
.To<Security>()
.InSingletonScope();
var command = container.Get<PrintInvoiceCommand>();
command.Execute(invoiceId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment