Posted on March 6th, 2009%
A coworker of mine (who just got back from the Microsoft MVP events in Seattle, congrats, Matt!) has turned me on to using Moq, which I must say is an impressive mocking framework that has made unit testing notably easier.
Recently I had the need to mock the IRequest interface of the Castle MonoRail framework – specifically, two properties: the indexed property and the QueryString property, both of which expose a NameValueCollection.
I found some guidance on mocking the indexed property via Stack Overflow, which turned me on to the following solution.
var request = new Mock<IRequest>();
request.ExpectGet(r => r[It.Is<string>(x => x == "someName")]).Returns(“someValue”);
To mock the QueryString property took a different approach: create a NameValueCollection, add my test data to it, and wire the collection to the mocked object.
var request = new Mock<IRequest>();
var query = new NameValueCollection();
query.Add(“someName”, “someValue”);
request.ExpectGet(r => r.QueryString).Returns(query);
With this, I can now pass my mocked IRequest to other classes, which will be able to access the following:
request["someName"] = “someValue”;
request.QueryString["someName"] . . .
→ Read More: Mocking indexed properties with Moq
Posted on January 14th, 2009%
[Digression] This post has been sitting in a somewhat unfinished state for a long time. It feels good to finally post it!
In rewriting my baseball game, CSFBL, I made the decision to use Castle ActiveRecord (built on top of NHibernate) to handle the persistence of my domain model. As a result, I needed to find a simple but effective way to unit test this implementation.
The unit tests needed to accomplish the following:
- Test the initialization of ActiveRecord (which validates the database schema against the object mappings).
- Test object validation (since I am using Castle’s Validation component and the
ActiveRecordValidationBase<T> base class).
- Ensure that a domain object can be persisted to the database.
- Ensure that a domain object can be retrieved from the database.
- Ensure that multiple instances of an object with the same persisted primary key are equal.
How, then, do we do this? . . . → Read More: Unit testing an Activerecord domain model with NUnit
Posted on December 8th, 2008%
The other day I started working on a WMI wrapper that would encapsulate workstation management functionality (starting and stopping services, querying workstations, etc.). Unit testing, as always, is important, but I inevitably came to one problem.
How do you unit test a method that reboots a workstation?
The answer: Run the unit test, and if your machine starts to shut down, that means it’s the end of the workday, and your test passed. (It was already 6PM on a Friday, so such behavior . . .
→ Read More: Unit testing a WMI reboot
Recent Comments