Anonymous Do by Mark Seemann
In unit testing an important step is to exercise the SUT. The member you want to invoke is often a method that takes one or more parameters, but in some test cases you don't care about the values of those parameters - you just want to invoke the method.
You can always make up one or more Dummy parameters and pass them to the method in question, but you could also use one of AutoFixture's Do convenience methods. There are several overloads that all take delegates that specify the action in question while providing you with Dummies of any parameters you don't care about.
A good example is WPF's ICommand interface. The most prevalent method is the Execute method that takes a single parameter parameter:
void Execute(object parameter);
Most of the time we don't really care about the parameter because we only care that the command was invoked. However, we still need to supply a value for the parameter when we unit test our ICommand implementations. Obviously, we could just pass in a new System.Object every time, but why not let AutoFixture take care of that for us?
(You may think that new'ing up a System.Object is something you can easily do yourself, but imagine other APIs that require much more complex input parameters, and you should begin to see the potential.)
Here's a state-based unit test that verifies that the Message property of the MyViewModel class has the correct value after the FooCommand has been invoked:
[TestMethod] public void FooWillUpdateMessage() { // Fixture setup var fixture = new Fixture(); var sut = fixture.CreateAnonymous<MyViewModel>(); // Exercise system fixture.Do((object parameter) => sut.FooCommand.Execute(parameter)); // Verify outcome Assert.AreEqual("Foo", sut.Message, "Message"); // Teardown }
Notice how the Do method takes an Action<object> to specify the method to invoke. AutoFixture automatically supplies an instance for the parameter parameter using the same engine to create Anonymous variables that it uses for everything else.
The Do method in question is really a generic method with this signature:
public void Do<T>(Action<T> action);
There are also overloads that take two, three or four input parameters, corresponding to the available Action types available in the BCL.
These methods are simply convenience methods that allow you to express your test code more succinctly than you would otherwise have been able to do.