Basically, I have a method on my class that invokes an Action<T> if certain conditions are met. How can I unit test to ensure that the action is invoked?
public class MyClass<T>
{
private IDBService _dbService;
private Action<T> _action;
public MyClass(IDBService dbService, Action<T> action)
{
if (dbService == null) throw new ArgumentNullException("dbService");
if (action == null) throw new ArgumentNullException("action");
_dbService = dbService;
_action = action;
}
public void CallActionIfPossible(T param)
{
if (_dbService.IsTopUser)
action(param);
}
}
Well, the basic idea is that the
Action<T>produces some state change somewhere (if it doesn’t, what’s the point?). So, unit test that the expected state change occurs when the conditions hold, and that the expected state change doesn’t occur when the conditions do not hold.Of course, ideally, you mock the
Action<T>so that the state testing is super easy. You do not need Moq or any other mocking framework for this:and
Of course, I don’t know your exact setup. Maybe you pass in
actionon construction ofBar, or maybe you have some other way of setting the action. But the idea should be clear.