Pex
Looks like Pex is out and ready for us to play with, seems like interesting stuff and as well as Peli posting up links to docs you can also view Ben Hall's first impressions.
In addition it looks like MbUnit can already be used with it.
Technical blog.
Looks like Pex is out and ready for us to play with, seems like interesting stuff and as well as Peli posting up links to docs you can also view Ben Hall's first impressions.
In addition it looks like MbUnit can already be used with it.
Posted by
Colin Jack
at
5/29/2008
0
comments
Pat Maddox has a superb post called Refactoring with Shared Example Groups which describes one strategy that Ruby programmers can consider when deciding how they want to change their tests when they extract a class/method in the SUT.
I'd guess you could use a similar solution in C# especially if you hooked into a test framework like Gallio, mind you it might be equally sensible to look at IronRuby for testing (longer term).
Posted by
Colin Jack
at
5/15/2008
0
comments
Labels: Ruby, TDD, Unit Testing
Discussions at ALT.NET and with Greg Young made me realize that I need to get more into messaging so I thought I’d start with a piece of work I’m doing now that is ripe for a bit of messaging. The piece of work relates to domain events, when an event happens in the domain (e.g Customer becomes active) we generate a message which subscribers can pick up. Generating an MSMQ message and sending it to subscribers seems sensible.
The obvious framework to look at was NServiceBus but Mass Transit is an alternative which I decided to try. Whilst playing with it I thought I'd write up my discoveries in the hope that someone might be useful and also produced a little sample project which you can download here.
First I should add some caveats:
Note that this sample contains a copy of some the Mass Transit code, I've done this to make it easier to setup/debug but the code will quickly go out of date so it is certainly worth downloading the latest copy.
If you want to run the different parts of the example then you can do so using the binaries in the TestAppBinaries folder. The parts of the solution are:
Debugging wise I found I could only really follow one app at a time, so I might start SubscriptionManager and Receiver and then debug Sender and then check that it correctly finds out about and processes the fact that Receiver wants to know about FootbalResultMessages.
Currently you must start the Receiver before the Sender or the behaviour will not be as expected, I will look into the reasons for this.
The world revolves around the ServiceBus class which has several methods that you can use to send messages:
Send/Deliver are fine and I do use them but they do not promote truly loose coupling, in many cases you won't want to specify the destination when sending the message and so I’m really more interested in Publish. You can see this if you look at Sender class (well its a static Main method, but hey this is just sample code) as it contains the following line:
bus.Publish(new FootballResultMessage(message))To understand the way that the Publish approach works you need you need to look at how the ServiceBus manages subscriptions...
I'll explain one potential way of handling these two parts using Mass Transit.
Adding/Removing Subscriptions (Receiver)
A subscriber sends an AddSubscription message to the ServiceBus when it wants to subscribe to a particular kind of message. The AddSubscription message takes two parameters, the message name and the URI (which in our case means MSMQ queue) to send messages of that type to.
To see how this works look at SubscriptionBasedMessageProcessor, in the Subscribe method it registers its interest in the message type that it is setup with. This registration involves the AddSubscription message being sent to the SubscriptionManager. In addition we specify a delegate (callback) that will be run when a message of the specified type arrives.
The code that sends the AddSubscription message is in MsmqUtil:
private static void SendSubscription(ServiceBus bus)
{
AddSubscription subscriptionMessage = new AddSubscription(MessageName, bus.Endpoint.Uri);
SendSubscriptionUpdate(bus, subscriptionMessage);
}
private static void SendSubscriptionUpdate(ServiceBus bus, SubscriptionChange subscriptionMessage)
{
MsmqEndpoint publishersQueue = "msmq://./subscriptions";
bus.Send(publishersQueue, subscriptionMessage);
}
You can see that in this case I'm sending an AddSubscription message to the central subscription management queue saying that football result messages should be sent to the ServiceBus that is passed in (which is the same queue that the BasicMessageReceiver is listening on).
Managing Subscriptions (SubscriptionManager)
My centralized store needs to maintain the list of subscriptions and also provide a way for interested parties to find out about them:
Since all I needed was in-memory supported I used LocalSubscriptionCache. Not that I had to make LocalSubscriptionCache implement ISubscriptionRepository so that I could use it with SubscriptionService, however this was a trivial change. The code that registers the cache is:
LocalSubscriptionCache cache = new LocalSubscriptionCache();
ServiceBus bus = new ServiceBus(subscriptionQueue, cache);
SubscriptionService subscriptionService = new SubscriptionService(bus, cache, cache);
subscriptionService.Start();
To see this code at work put a break point in MsmqMessageReceiver.ProcessMessage, start SubscriptionManager in the debugger and then open Sender which causes a cache update request message to come in for processing. You should end up debugging into SubscriptionService.HandleCacheUpdateRequest which ensures the appropriate response is sent back to the caller.
One interesting thing to note is that when Sender sends off the CacheUpdateRequest it puts the return address as its own ServiceBus' end point (the MSMQ queue it is working from). The reply message is picked off this queue by MsmqMessageReceiver and is then routed to the SubscriptionClient which has registered its interest in the reply.
Requesting Subscriptions (Sender)
I've now managed to get my subscriptions registered with a centralized queue (backed up by SubscriptionManager), however I need to make sure that I can get the latest subscriptions when I need them. Luckily this is easily accomplished using the SubscriptionClient:
SubscriptionClient subscriptionClient = new SubscriptionClient(bus, bus.SubscriptionCache, subscriptionServiceEndpoint);
subscriptionClient.Start();
This class ensures that I am kept up to date as subscriptions are updated, for example if an AddSubscription is processed by the centralized service then it will be distributed back to my service which will cause SubscriptionClient.CacheUpdateResponse_Callback to execute (NOTE: I'm not sure I've fully understood this functionality yet and it is not working quite as I expected so this last statement may not be correct).
One key thing I learned when working on this was how key the queue that you pass into a ServiceBus on construction is, this queue is the one that the ServiceBus looks for messages on.
To see how key it is you can write a simple code example and follow it through. Create a ServiceBus then call Subscribe and pass in any old delegate before publishing a message of the same type using Publish.
When you run the code you can see a few things:
This setup makes a lot of sense as the behaviour is the same regardless of the messages origin, so a message coming into the ServiceBus’ queue from outside is treated the same as a message that the ServiceBus adds to its own queue.
Posted by
Colin Jack
at
5/05/2008
0
comments
Labels: Design, Mass Transit, Messaging
Thought I should write up the sessions that I most enjoyed at ALT.NET Seattle, because otherwise I'll forget it all.
Jeremy Miller had a superb session on how he's managed to maintain Structure Map over multiple years, and how focusing on good OOD made it very easy to maintain the code base. Very enjoyable and look forward to reading more about what it's taught him about writing tests that support you well when you do big refactoring/redesign. The best bit was undoubtedly when he was asked what IoC he uses, superb.
Scott Bellware did a session on the context/specification style of BDD which was interesting and reminded me to read his Code magazine article. I like the context/specification approach and it kinda seems like the whole story/scenario based approach has (temporarily?) stalled in the .NET world so it was good to hear about how Scott makes context/specification work. I need to look more about how to write good acceptance tests though because I've never been happy with the results.
Greg Young and others contributed to and organized several excellent session future architectures, videos of two of them are up here and here.
There was also a good discussion of messaging at a .NET scalability session, Dru Sellers providing the expertise and it left me wanting to try out Mass Transit.
There were plenty of other good sessions with interesint contributions, in many cases though I wasn't sure who was contributing (no name tags, argh) so I don't know where to go for more info.
Posted by
Colin Jack
at
4/30/2008
0
comments
Labels: ALT.NET
BDD Divergence
The BDD Acceptance Testing thread over at the BDD forum is showing up what I consider to be the big problem in BDD at the minute, mixed messages.
On one side you have an approach that uses a context and specification approach to apply BDD style tests to all levels of specification, this is the approach where you might have a class called When_my_account_is_declined containing a specification called A_notification_is_sent_to_interested_parties. In my view this style is useful, I've been using it for unit testing and I like it a lot. Having said that I'm not intending to take a dump of the context/specification names for use by non-programmers in the team (e.g. domain experts) because a lot of the specifications will be too low level or technology focused. So far I'm primarily using this style to get nice readable specifications for use by the developers, so as a different style of TDD.
On the other side is the story/scenario driven approach that Dan North is pushing for, he also describes why he likes to separate these tests from classical programmer tests and the part they play in your process.
I personally think that you can use the two approaches together if you want to, using the given/when/then approach for acceptance tests and context/specification (or just normal TDD) for all other tests (including unit tests). You can of course use the context/specification style for the acceptance tests and dump given/when/then. Whether this is a good idea depends on whether the benefits Dan's approach brings (such as improving communication with non-programmers in the team) justify the effort of using the given/when/then style and to be honest I haven't used his style enough yet to have a strong view on it.
Are we automating Stories or Scenarios
Two interesting points that Dan makes in the acceptance testing thread are:
"As you quite rightly said, you can express any scenario in just a regular
example, or xunit test case."
..and..
"The scenario runner (not story runner - you don't run stories)"
He is clarifying that we run scenarios not stories. What is a scenario in this context, Scott gives a good definition in the BDD terminology thread:
"A scenario is a way to express acceptance criteria using an example-
driven approach. A scenario can express more than one criteria if
needed. "
The fact that you automate scenarios rather than acceptance tests is a good point to make.
Terminology
In the discussions on BDD we all seem to use consistent terminology, however the BDD terminology thread at the BDD forum is a good starting point to getting some consistency (which can only improve the discussion).
Posted by
Colin Jack
at
4/27/2008
2
comments
Labels: BDD, Unit Testing
Just got back from a holiday in Vancouver and Seattle.
The highlight was a whale watching trip with Wild Whales Vancouver. We were lucky enough to see plenty of wildlife and in particular a pod of transient killer whales hunting a porpoise, apparently witnessing such a thing is quite rare and it was definitely a great experience. We haven't yet looked at our own pictures from the day but a research vessel that was nearby got some super pictures which are available here. My favourite is:
Definitely recommend whale watching and Wild Whales Vancouver. It was also interesting to hear about the issues affecting killer whales around Vancouver and to find out that Canada isn't actually quite as enlightened on environmental issues as people in Europe might expect.
Posted by
Colin Jack
at
4/25/2008
0
comments
Looks like there Stefan Lieser has created a Resharper plugin that will help ensure your HBM's are kept up to date when you refactor. Seems its still at an early stage but it should prove very useful.
Achmed has also put together a log4net Resharper plugin which could also be very useful.
There is also a thread on both in the Resharper forum.
Posted by
Colin Jack
at
3/27/2008
1 comments
Ayende has a post about how Udi Dahan uses role interfaces in the domain, specifically to allow optimizations of fetching.
Its an interesting enough idea, though I'm not really sure on it, but it did also lead to someone linking to Fowler discussing role interfaces. Never seen that particular page before but it was very relevant and I liked the term for the alternative approach, header interface.
Posted by
Colin Jack
at
3/27/2008
0
comments
Whilst playing with using BDD style specifications to drive the granular design of my classes I've tried to see if I can also look at ensuring my tests are as readable as possible and I thought I should document my current thoughts on the results.
In this description I'll use the word specification/test interchangeably...I'm just not ready to talk about state or interaction specifications.
I've been following the approach of having small test fixtures (contexts), for example:
using Concerning = System.ComponentModel.CategoryAttribute;
using Specification = NUnit.Framework.TestAttribute;
using Context = NUnit.Framework.TestFixtureAttribute;
using NUnit.Framework;
namespace AddressMapperSpecifications
{
[Context]
[Concerning("AddressMapper")]
public class When_mapping_addresses
{
#region Fields
private AddressDetails _mappingFrom;
private Address _mappingTo;
#endregion
# region Context
[SetUp]
public void SetupContext()
{
_mappingFrom = AddressObjectMother.CreateAddress();
_mappingTo = new AddressMapper().Map(_mappingFrom);
}
# endregion
#region Specifications
[Specification]
public void Street_one_is_mapped()
{
Assert.AreEqual(_mappingFrom.StreetOne, _mappingTo.StreetOne);
}
[Specification]
public void Street_two_is_mapped()
{
Assert.AreEqual(_mappingFrom.StreetTwo, _mappingTo.StreetTwo);
}
I like this style because it leads me to have small fixture/context classes, likely only a very few specifications are going to want to share exactly the same fixture so I avoid the issue of my classes getting too big.
I also think that the small fixture size and the class/test names together result in an approach that I find very readable.
As I see it you use use mocking for a few reasons, one of the most obvious ones is to for convenience. Say A calls B which calls C, if I write my tests for C but my clients use A then I need to show that when I call A we can expect C in turn to be called (and also can show the arguments/return values). I see this as mocking to make granular testing easier, there are other reasons to use mocking/stubbing but this discussion doesn't necessarily relate to them so well.
The previous example showed a state test/specification where just having an assertion (or assertions) in the specification method worked. Arguably moving the setup and interaction with the system under test (SUT) into the SetupContext method helped make it all more readable. We can't really do that so easily with mocking tests because in a mocking test you have to setup your expectations up front so the tests take take (basically) this form:
If we move the setting up of the mocks into the SetupContext method then we'd end up with a situation where each class had one specification (because its unlikely we'll want to setup the same expectations multiple times). Even worse looking at the specification method would tell you nothing because to understand a mocking test you need to start by looking in detail at the expectations.
I've thus found that so far my interaction tests are taking this form:
namespace AccountMessageMapperSpecifications
{
[Context]
[Concerning("AccountMessageMapper")]
public class Interactions_when_mapping_an_account : RhinoMockBase
{
# region Fields
private Account _subjectOfMessage;
private DomainMessage _messageToBeMapped;
private AccountMessageMapper _underTest;
# endregion
#region Context
[SetUp]
public void SetupContext()
{
_subjectOfMessage = AccountObjectMother.CreateAccount();
_messageToBeMapped = new TestDomainMessageBuilder().WithDomainEntity(_subjectOfMessage).Build();
_underTest = new AccountMessageMapper();
}
#endregion
#region Specifications
[Specification]
public void Primary_address_is_mapped()
{
IMapper<IAddress, Address> _mapper = Mocks.CreateMock<IMapper<IAddress, Address>>();
using (Record)
{
Expect.Call(_mapper.Map(_subjectOfMessage.Owner.PrimaryAddress)).Return(new Address());
}
using (Playback)
{
_underTest.Map(_messageToBeMapped);
}
_mocks.VerifyAll();
}
#endregion
}
}
DISCLAIMER: I've just bodged this together so it isn't great. I'm particularly not liking the way it looks when I pass a generic interface in to get a mock for it!
Most of the code is in the actual specification method, including all of the setup, the interaction with the SUT and finally the call to verify that the expectations were met. I've moved as much as I think I sensibly can into the SetupContext method but the fixture is still quite lightweight and reusable, for example I could easily put another method in that showed the interaction with another mapper (e.g. Telephone_number_is_mapped).
Overall though I think this style of interaction test is quite readable, and to me the combination of the two tests explains very well the behaviour of a low-level component (AddressMapper) and also the interaction that a higher level component (AccountMessageMapper) has with it.
Posted by
Colin Jack
at
3/25/2008
0
comments
Labels: BDD, Interaction Testing, Mocking, TDD
Lets say we want to map this class hierarchy:
Table wise we only have one table called MultipleClassesToOneTable:
So we're trying to map MainClass and MainClassKind to a single table and we want it to handle the fact that MainClassKind has subclasses. Why are we doing this, because we're working with a pre-existing database that is hard to work with.
Ideally we want MainClassKind to behave like a <component> but we can't map it that way because <component> does not support inheritance so the question is how do we map it?
MainClass
This is the class that would act as our aggregate root and which will manage the ID, its mapping is quite simple:
<class name="MainClass"
table="MultipleClassesToOneTable" lazy="false">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<one-to-one name="Kind" access="property" cascade="all-delete-orphan" />
</class>
Note that this class is mapped to MultipleClassesToOneTable and its generating the identity value which is stored in Id. The class also has an association to a MainClassKind, but its a pretty dull ordinary mapping file.
MainClassKind
If we could map this class as a component of MainClass then we would, since we can't we have to do something a bit more interesting:
<class name="MainClassKind" table="MultpleClassesToOneTable" lazy="false">
<id name="Id" column="Id" >
<generator class="foreign">
<param name="property">MainClass</param>
</generator>
</id>
<discriminator column="Kind" insert="false" />
<property name="Kind" access="property"/>
<property name="Description" column="Description" />
<one-to-one constrained="true" name="MainClass" access="property"/>
<subclass discriminator-value="0" name="FirstKind" >
<property name="FirstClassesExtraValue" access="property"/>
</subclass>
<subclass discriminator-value="1" name="SecondKind"/>
</class>
So what is notable about this mapping:
Hrm...
Result
Well I'm not exactly happy with this mapping, it seems like a hacky way of getting the behaviour I want, but I guess its an option if you really want to redesign your model in such a way without redesigning your database. Is there a better way to handle this though?
Posted by
Colin Jack
at
3/24/2008
4
comments
Labels: NHibernate
I've been using Windsor on a Windows service for the last couple of weeks and the nastiness of its XML files quickly became a pain.
I don't tend to mind XML too much, for example I think the XML configuration option with NHibernate is pretty good, but Windsor's is just way too wordy and repetitive.
Anyway I had another look at Binsor but having to learn Boo and the DSL itself is hard enough and without IDE support (other than SharpDevelop) I thought it was too much.
Good news is it looks like there is already a fluent interface project for Windsor. You can read about it at Hammett's blog (or in this dev thread), there is also a blog entry about an approach that allows automatically registering services from an assembly. All very good and examples
Posted by
Colin Jack
at
3/21/2008
2
comments
Labels: Castle, Dependency Injection, Design, IoC
Chad Myers has a post on LSP, the example isn't technically of LSP (see comments) but it did make me think of one of my pet peeves in the .NET framework.
As you may know you can call List<T>.AsReadOnly and get back a read-only wrapper, you get back an object that supports IList<T> so you try to use it:
List<string> dinosaurs = new List<string>();
ReadOnlyCollection<string> asReadOnly = dinosaurs.AsReadOnly();
((IList<string>)dinosaurs).Add("Tyrannosaurus");
((IList<string>)asReadOnly).Add("Bob"); // kablam, NotSupportedException
Now looking at the documentation the exceptions are made clear, for example on ICollection<T>.Add. This means that it's not an LSP violation, but it does annoy me because it means that most of the methods on IList<T> will raise exceptions if they are not suitable for use with the actual type behind the interface.
And remember this could be a real problem. For example your method had been accepting List<T> and had been calling Add on that class. You decide that its nicer to use base types where possible so you change the method to accept IList<T> and now your open to being passed a ReadOnlyCollection which will immediately blow up.
So why is the design the way it is, dunno. Does seem like it was discussed but it's not a decision I like. I'd have probably had a specific IReadonlyCollection<T> interface. In fact we have that interface in our code base and we've found it very useful indeed, particularly in the domain where we want to make clear when things are read-only without having to resort to exceptions.
If you don't know what LSP is then read this PDF or even this link (which I found whilst searching for the PDF) but really to get your head around a lot of this stuff you need to go to the books, in particular Agile Principles.
Posted by
Colin Jack
at
3/18/2008
2
comments
Labels: Design
I was reading James Kovacs' MSDN Magazine article Tame Your Software Dependencies for More Flexible Apps. I spent some time writing some comments to put in the related blog entry but I thought I should write up my thoughts in a little more detail because I do think that my views on dependency inversion principle (DIP) differ from other peoples.
First off what is DIP, if you don't know then go read Robert Martins description and/or do a search on Google because there is lots of stuff out there (including this article by Jeremy Miller).
Testing is often the underlying reason that people push for DIP. That's a big pity because it leaves people thinking that DIP is only useful for testing, which is nonsense.
So lets go back to some of the reasons Robert Martin introduced DIP:
So how do we violate DIP, well we can easily do it by making our domain logic depend on implementation details. Put your repositories implementation in the same project as the domain logic and call those repositories from the domain and you've got it (though the repository classes do provide some encapsulation of the details). Likewise coupling your domain logic to a specific logging framework, or maybe to a specific vendors API.
So DIP is great, no doubt, an a sensible principle. However I disagree with some of the forum entries/blog posts and so on about DIP...
So let me make clear again, I don't have a problem with DIP, in fact I think it is very useful. However I do have an issue with the way people describe DIP because in many cases it differs from my experience, here are the issues I have with some of the writing about it:
Note when I discuss interfaces above I'm talking about naive interfaces, OrderRepository having an IOrderRepository interface (interface-implementation pair). If you are creating small role interfaces (ISP) and are giving the resulting interfaces more domain meaning (IOrderBook) then you are absolutely doing a good thing. Even better if the interfaces you define are customized for the specific clients. However I think that few, very few, articles on IoC/DI/DIP focus enough on these things.
Personally I think a lot of talk about DIP/DI/IoC misses the key point, design. Too many examples focus on details like how you configure your container and assume the natural pre-eminence of the interface approach.
I think this is a bit of a mistake, like I say I like interfaces but I am usually skeptical about the ICustomerRepository style approach because in many places I think people use that style without thinking about what real benefits they are getting.
In our case our service layer directly creates repositories/domain service layer when it needs them. This could backfire, for sure, but so far I'm not convinced that its a big mistake and if we find that it was wrong it will be relatively easy to change. Am I violating DIP when my service layer contacts a repository directly, yes. However I'm doing it with my eyes open and (I hope) with a good understanding of the consequences.
My advice would be, before going out and learning about Windsor/Binsor and the rest find out a bit more about DIP and why its useful, that way you can judge for yourself how to proceed.
Posted by
Colin Jack
at
3/17/2008
1 comments
Labels: DDD, Dependency Injection, Design, IoC, Object Oriented Design
Really just posting this to give myself an easy link to this blog entry with tonnes of DDD links.
Posted by
Colin Jack
at
3/17/2008
0
comments
Just re-reading Dan North's article Introducing BDD and realized that I'd forgotten about this section:
At first, the fragments are implemented using mocks to set an account to be in credit or a card to be valid. These form the starting points for implementing behaviour. As you implement the application, the givens and outcomes are changed to use the actual classes you have implemented, so that by the time the scenario is completed, they have become proper end-to-end functional tests.
I must admit I haven't tried this approach yet but it is one that makes sense to me so I think I'll try it because I really think having end-to-end functional tests is very attractive.
Posted by
Colin Jack
at
3/14/2008
2
comments
Labels: BDD, TDD, Unit Testing
In a TDD thread on tests as specifications there was a link to Uncle Bob talking about Stable State: An Emergent Rule, an excerpt is:
If you look carefully at the specification of the Bowling Game you will see that the state of the Game is changed only by the setup block within the context blocks. The specify blocks simply interrogate and verify state. This is in stark contrast to the JUnit tests in which the test methods both change and verify the state of the Game.
Really its the same idea as some people practicing BDD have, keep the test/specification methods small and preferably just doing Assertions (or mock verifications I guess).
Posted by
Colin Jack
at
3/14/2008
0
comments
Labels: BDD, TDD, Unit Testing
Some of the articles on BDD put a heavy emphasis on mocking and outside-in development.
However so far the discussions on the BDD group seem to have left me feeling that when to mock is just as much of an issue in BDD as it is in TDD. Having said that as I try BDD I'm making sure I also spend the time to think about the ways I use mocking, just to formalize my thoughts.
Some of this is just my unordered thoughts, just stuff I'm thinking as I write the specifications using BDD. I've broken it down to sections based on the reasons I'm mocking.
I've been trying to do some outside-in style mocking as I go, I've discussed this in an earlier post but I am finding that thinking about collaborations (for Services at least) is quite an interesting technique. I've tried it in the past and didn't like it too much, but I think I'm now at a stage where I'll try to work it in to my normal practices.
I think I'm using the technique naively though. For example I ended up writing up-front mocking tests for an XmlFileBasedSender which takes in a DTO and ensures its packaged as XML and put in a suitable file. I blindly followed the technique but ended up with what I consider to be a pretty silly design:
public XmlFileBasedSender(IXmlFileNameProvider fileNameProvider, IConfigurationService xmlConfigurationService,
IFileSystem fileSystem, INotificationToXmlConverter notificationMapper)
To me INotificationToXmlConverter and IXmlFileNameProvider are just small lightweight strategy/helper/policy classes where as the other two are meaningful abstractions (especially as with them I'm wrapping built in .NET framework functionality). I'd think this style of constructor is more meaningful:
public XmlFileBasedSender(IConfigurationService xmlConfigurationService, IFileSystem fileSystem)
To be fair this isn't a problem with the technique, I've probably just gone overboard and at mockobjects.com Steve Freeman was good enough to point out that he might have just written an integration test for the service and might have encapsulated the little policy classes.
Of course even if I do just have XmlFileBasedSender create the instance of NotificationToXmlConverter in the constructor I might want to stub out NotificationToXmlConverter. In that case I'm stubbing for convenience rather than to use it as a design technique, but I think that's OK (especially since we use TypeMock).
I'm also not planning to use this technique all the time, I think state based testing is still often the way to go and that in many cases I'll stub rather than mock but that's not to say that this technique doesn't have its place. I especially liked using it in combination with integration tests. So after writing interaction tests for XmlFileBasedSender I wrote tests for each of the dependencies and then wrote a single integration test for XmlFileBasedSender (at which point I discovered I'd forget to create a class implementing IClock).
Finding the balance between mocking/state tests and between integration/unit tests is something I'll continue to think about, though presumably never coming to a conclusion on.
I needed to mock out calls to DateTime.Now and File.Create, using TypeMock to mock these would not be a good idea and anyway I'm happy enough to wrap in these cases (though wrapping DateTime.Now is a little irritating). There's lots out there about wrapping like this but essentially I ended up with tests like this (using string based mocking because I'm using the free version of TypeMock for the example):
[TestMethod]Technically I guess this is mocking for design, but even if I wasn't using mocking as a design technique I'd still need to wrap the file system and clock just to allow me to stub them out.
public void Current_time_retrieved_from_clock()
{
#region Setup Expectations
Mock mockClock = MockManager.MockObject(typeof(IClock));
mockClock.ExpectGet("Now", DateTime.Now);
IClock clock = (IClock)mockClock.MockedInstance;
#endregion
new ClassUnderTest(clock).DoSomething();
}
ClientMapper uses a ClientFeeDestinationMapper so I've written tests for the ClientFeeDestinationMapper and then written one test that proves that the ClientMapper interacts with the ClientFeeDestinationMapper. This test was not about working out role interfaces so this is not me using mocking as a design technique and I just used TypeMock to mock out the concrete ClientFeeDestinationMapper.
One problem with this is that the tests (including the state ones) are very granular so any change means re-writing them. For example I plan to try using Otis (XML based object-object mapping) again, at which point ClientFeeDestinationMapper will probably disappear and ClientMapper will do everything (everything being kicking off the mapping process). Now in order to do that I first need to re-write my tests, which is a pain but not really related to the fact that I'm mocking or to BDD.
Posted by
Colin Jack
at
3/11/2008
0
comments
Labels: BDD, Mocking, TDD, Unit Testing
I'd previously posted about NHibernate Gotchas but we just came accross a big one, cascade options on one-to-one.
Essentially we'd used the cascade option "all-delete-orphan" on a
Unfortunately the cascade option was totally ignored and indeed after quite a bit of effort we found that the docs do indicate its not supported an its a known issue.
Workarounds, not sure. Deleting the one-to-one from the ISession directly is not an option for us in our POCO domain so we may need to look at other mappings.
Worth knowing anyway!
Posted by
Colin Jack
at
3/11/2008
6
comments
Labels: DDD, NHibernate
We've recently been putting in the Party archetype for managing information about People/Organizations and their roles in regards to our systems. When mapping the roles we had two good choices:
Our database expert(s) preferred us to choose the latter, particularly because some of our roles do not have extra information and if we'd gone for table-per-subclass we'd have given those roles their own (pretty much empty) tables.
Unfortunately the join-table approach has issues, not least that the join-tables cannot support their own components so we changed our mind and instead went for the table-per-subclass approach. The amazing thing is that one of my colleagues, Kathryn, managed to make this change and have our tests passing in no more than a couple of hours.
This is brilliant, all it required was a few changes to the mappings, creation of a couple of tables for the roles that weren't (currently) adding any data and a couple of update scripts to ensure those tables were populated and that the discriminator column was removed from the party role table.
Posted by
Colin Jack
at
3/10/2008
1 comments
Labels: Design, NHibernate
For now I'm ignoring the story based approach to BDD, I still think it's probably going to be useful but I'm not sure I'm yet in a place where I can take advantage of it so I'm just going to focus on the specification style. Doing it this way is also simpler because in my view the specification based approach is just "better TDD" but the story based approach seems to me to be a bit more fundamental and affects more than the developers.
I've gone for this style of test class/method naming:
class When_mapping_a_customer
Name_is_mapped()class When_grouping_related_domain_changes
...
All_changes_for_an_entity_are_grouped()
...
I'm enjoying naming tests in this sort of style, I've toyed with a few other approaches but this one has so far kept me happy as the class/test names are not too long but they are quite expressive.
I've taken out all the "should_" from the tests because it felt like noise especially when I viewed the list of test names in the IDE.
Of course this is very similar to the approach others have specified, including Agile Joe and there will certainly be better naming schemes around.
Some seem to see BDD as primarily being about making it easy to trace a specification (test) back to its context. You start out with a context (small test fixture for a particular case) and then write your specifications, most of the code ends up in the test class setup method and the tests themselves are nice and small. You don't just end up with one big CustomerTest class full of tests that require different fixtures or which are for different features.
I do find that BDD's style of having lots of test classes (small fixtures) and attempting to have one line of code in the specification (test) method can make it easy to understand what is being specified.
It's not all good though, one of my colleagues points out that he likes to see all of the code in the test method.
We were also slightly worried by the fact that the specifications for a class end up fragmented across quite a few files, which is fine but you might have some fun finding the specification for behaviour for a particular class in a large code base. I'm getting around this at the minute by tagging the fixture classes with a [Concerning("AccountMapper")] as discussed by Agile Joe, you can then search for the class name and find all the specifications. Not very advanced though, but then again it will improve if tools come in that support the BDD style.
Oh and Brian Donahue has a post on the same sorts of issues so I'm not alone in think about this, and I'm sure they are issues that many other people are dealing with.
At the moment I'm not using any special framework for these specifications at the moment, which I think is a valid choice (for now). I'll probably look again at the specification side of NBehave and at SpecUnit.NET but it seems too early to be using either on commercial projects at the moment.
Initially my reaction was that this is really just TDD with a test class per fixture policy that focuses on really small fixtures. It hardly seems like a fundamental change, but having done it I think the combination of naming and small test fixtures is quite useful and could (perhaps) lead to people doing TDD "properly".
This is probably only interesting to a few people but there are issues with using these approaches in Team System. Nothing major but annoyances.
For example you cannot (as far as I can see) re-alias [TestMethod] to be [Specification]. Also the test list window is ridiculously constricting and there is (so far) no support for integrating other test runners into Team System.
There may be workarounds for some of these issues, for now I'm ignoring these topics though and just doing the best I can.
Posted by
Colin Jack
at
3/05/2008
0
comments
Labels: BDD, Design, Unit Testing