Last time I talked about creation of Fake objects in our Visual Basic APIs, as well as handling future objects. Today we continue are journey in VB land. Let’s see how we can set behavior on functions and assert that calls happened.
Here’s a Visual Basic code example on setting a result.
1 |
Using TheseCalls.WillReturn(200.0F)<br /> fakeProduct.CalculatePrice(0)<br /><span class="kwrd">End</span> Using |
Really simple. And since its VB, you can put multiple statements in that Using clause, which have the same behavior. With TheseCalls you have the following options:
- WillReturn – returns a value, instead of invoking the Function. Note that this is not type-safe. If you return a value of a different type than the Function returns, you’ll get a run-time exception. The compiler allows it.
- WillBeIgnored – ignores the method. Used for Subs, not Functions.
- WillThrow – throws the specified exception
- WillCallOriginal – executes the original Function or Sub code.
- WillReturnRecursiveFake – Self explanatory, really.
The Using clause is very simple to use. It’s also the basis for assertion, as we can see in the next code example:
1 |
Using AssertCalls.HappenedWithAnyArguments<br /> fakeProduct.ModifyPrice(0)<br />End Using |
Again this works for multiple calls, which is a lot more handy than its TheseCalls sibling. The options are:
- HappenedWithAnyArguments – asserts that the calls were made, regardless of arguments. Note that “happened” means “at least once”.
- HappenedWithExactArguments – The same, only asserting that calls were made with the specified arguments.
- NeverHappened – The calls were never made, with or without arguments.
Any call that breaks the assertion causes a nice VerifyException to be thrown.
So there you have it. Start using it. No more “VB is treated poorly by tool developers” crap. Time to write simple unit tests.