Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test.
Martin Fowler
[TestClass]
class TestStockAnalyzer
{
[TestMethod]
public void TestContosoStockPrice()
{
// Create the fake stockFeed:
IStockFeed stockFeed =
new StockAnalysis.Fakes.StubIStockFeed() // Generated by Fakes.
{
// Define each method:
// Name is original name + parameter types:
GetSharePriceString = (company) => { return 1234; }
};
// In the completed application, stockFeed would be a real one:
var componentUnderTest = new StockAnalyzer(stockFeed);
// Act:
int actualValue = componentUnderTest.GetContosoPrice();
// Assert:
Assert.AreEqual(1234, actualValue);
}
...
}
Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they got all the calls they were expecting.
Martin Fowler
import static org.mockito.Mockito.*;
@Test
public void testVerify() {
// create and configure mock
MyClass test = Mockito.mock(MyClass.class);
when(test.getUniqueId()).thenReturn(43);
// call method testing on the mock with parameter 12
test.testing(12);
test.getUniqueId();
test.getUniqueId();
// now check if method testing was called with the parameter 12
verify(test).testing(Matchers.eq(12));
// was the method called twice?
verify(test, times(2)).getUniqueId();
// other alternatives for verifiying the number of method calls for a method
verify(mock, never()).someMethod("never called");
verify(mock, atLeastOnce()).someMethod("called at least once");
verify(mock, atLeast(2)).someMethod("called at least twice");
verify(mock, times(5)).someMethod("called five times");
verify(mock, atMost(3)).someMethod("called at most 3 times");
}