Entity Framework Wiki
The EF team have created a Wiki where you can contribute your views on domain model focused development. Definitely a good sign as they are obviously very interested in finding out how we work.
Technical blog.
The EF team have created a Wiki where you can contribute your views on domain model focused development. Definitely a good sign as they are obviously very interested in finding out how we work.
Posted by
Colin Jack
at
6/30/2008
3
comments
Labels: Entity Framework
Three interesting posts have appeared. They started with Michael Feathers blogging about The Flawed Theory Behind Unit Testing, definitely worth a read.
Steve Freeman replied with Test-Driven Development. A Cognitive Justification? which itself had some very interesting points.
Another reply is TDD, Mocks and Design which is also very interesting and focuses on the reasons the advocates removing getters/setters and itss effects on design/testing.
Posted by
Colin Jack
at
6/15/2008
0
comments
Labels: TDD, Unit Testing
I watched Jim Webber's Guerilla SOA presentation at InfoQ this morning and he mentions the Soya project so I gave it a quick look.
It builds on top of WCF to allow you to substitute SSDL contracts for your normal WSDL ones, allowing a message based approach.
Luckily the documentation at the site is pretty good and the binaries come with a couple of useful examples including the one described in the getting started section so I definitely felt it was worth a few hours.
Posted by
Colin Jack
at
6/14/2008
0
comments
Labels: Messaging
I finally got around to looking properly at Spec#, previously all I've been going on was blogs and podcasts, and I'm very impressed.
Although there are other good resources out there I decided to write about the features I enjoyed using, and obviously if you want to try Spec# yourself you can get it at the Spec# Site.
Non-Nullable Reference Types
If you look at many of my protected or public methods then you'll find code that look out for nulls. Its not particularly interesting code so writing it and testing it is bad enough but for it to be visible to the users of your code you really also need to document it (unless the tests are enough).
Anyway there is little doubt that using ! to indicate that null is not allowed is a far more attractive option:
public void Transfer(Account! source, Account! destination, doubletransfer, IAuthorizationService! authorizationService)
If I then try to pass in null then I do get a warning telling me that "Null cannot be used where a non-null value is expected.", very nice.
Preconditions
I might want to specify some preconditions explicitly to help the caller know what is expected of them:
public TransferDescription! Transfer(Account! source, Account! destination, double amountToTransfer, IAuthorizationService! authorizationService)
requires source != destination;
requires amountToTransfer > 0;
If I now try and call my service passing in the same Account for source and destination then I get a Microsoft.Contracts.RequiresException which is useful.
This feature alone would be great for someone like me, not least as it makes it easy for callers to find about these preconditions:
PostConditions
Postconditions help me describe the promises my member makes to callers. For example here is how I've specified that my method returns a non-null object that contains the amount of the transfer:
public TransferDescription! Transfer(Account! source, Account! destination, double amountToTransfer, IAuthorizationService! authorizationService)
ensures result.Amount == amountToTransfer;
If the returned object does not have an Amount equal to amountToTransfer then I get a Microsoft.Contracts.EnsuresException.
Invariants
Specifying that some set of conditions "always" holds true can be useful, for example lets say I want my accounts to stay in credit:public class Account
{
private double _balance;
invariant _balance >= 0;
The result of breaking one of these invariants at run-time is an Microsoft.Contracts.ObjectInvariantException. There is also a way of temporarily breaking invariants within the type, see the expose keyword.
Finding Out More
Google doesn't turn up much until you realize that instead of Spec# you need to search for something like "specsharp". Still there isn't that much out there and in general the documentation regarding Spec# is pretty patchy but there are some decent resources:
I certainly thought Spec# was worth a few hours of play, I did only scratch the surface but I definitely hope these features are brought into C# sooner rather than later.
Posted by
Colin Jack
at
6/07/2008
0
comments
Labels: Spec#
It seems like when Pex generates failing tests the choice is between "Fix It" and "Allow It" and they do seem to do very different things so I thought it was worth mentioning what little I've found out.
I'll start out with this code in a Pex test:
[PexMethod]
[PexUseType(typeof(AuthorizationService))]
public void overall_behavior_correct(IAuthorizationService authorizationService,
Account source, Account destination, double amountToTransfer)
{
new AccountTransferService().Transfer(source, destination, amountToTransfer, authorizationService);
}
When I run Pex with this test it generates one passing test and some failing tests:
The failing tests are showing me useful things, for example the SUT does indeed raise an exception if the source and destination Accounts are the same. If I right click on either of these issues I get two options:
Fix It
If I select "Fix It" on each of the automatically generated tests then Pex ends up updating the original parameterized unit test (PUT) to look like this:
[PexMethod]
[PexUseType(typeof(AuthorizationService))]
public void overall_behavior_correct(IAuthorizationService authorizationService,
Account source, Account destination, double amountToTransfer)
{
// <pex>
PexAssume.IsNotNull((object)source, "source");
PexAssume.IsTrue(source != destination, "source == destination");
PexAssume.IsTrue
(source.Balance >= amountToTransfer, "source.Balance < amountToTransfer");
PexAssume.IsNotNull((object)destination, "destination");
PexAssume.IsNotNull((object)authorizationService, "authorizationService");
PexAssume.IsTrue(amountToTransfer >= 1.5, "amountToTransfer < 1.5");
PexAssume.IsTrue(((AuthorizationService)authorizationService).AllowTransfer
(source, destination, amountToTransfer) != false, "complex reason");
// </pex>
new AccountTransferService().Transfer(source, destination, amountToTransfer, authorizationService);
}
If I now run Pex again it will generate 0 tests from this code. I guess this makes sense, the PexAssumes are presumably telling Pex not to pass in certain values (such as null for source). However in the process I've made my PUT pretty useless and it does make me question the usefulness of the "Fix It" option in these sorts of situations, so "Allow It" must be the more sensible option in this case...
Allow It
If I select "Allow It" for each of the failing generated tests then my Pex test stays as it was originally but the following attributes are put into my assembly:
[assembly: PexAllowedExceptionFromAssembly(typeof(ArgumentException), "PexPlay")]
[assembly: PexAllowedExceptionFromAssembly(typeof(ArgumentNullException), "PexPlay")]
[assembly: PexAllowedExceptionFromAssembly(typeof(ArgumentOutOfRangeException), "PexPlay")]
[assembly: PexAllowedExceptionFromAssembly(typeof(InvalidOperationException), "PexPlay")]
PexPlay is the assembly I'm working in (the assembly that contains the SUT) and this seems to be indicating that if I get any of the specified types of exceptions anywhere in PexPlay then the tests should still pass. This is confirmed if I re-run Pex as it will generate the same set of tests but they now pass:
Problem is that the attributes are at too high a level for me to be happy, I'm not necessarily always happy to see those exceptions so instead of using PexAllowedExceptionFromAssembly I tried using attributes at the Pex test level which seems to work fine:
[PexAllowedException(typeof(ArgumentException)), PexAllowedException(typeof(ArgumentNullException)),
PexAllowedException(typeof(ArgumentOutOfRangeException)), PexAllowedException(typeof(InvalidOperationException))]
[PexMethod]
[PexUseType(typeof(AuthorizationService))]
public void overall_behavior_correct(IAuthorizationService authorizationService,
Account source, Account destination, double amountToTransfer)
{
new AccountTransferService().Transfer(source, destination, amountToTransfer, authorizationService);
}
Its probably worth noting how the PexAllowedException have effected the generated tests, here's one of them (MSTest):
[TestMethod]As you can see the test is marked with ExpectedException attribute which correctly specifies the behaviour I expect when I pass in a null Account.
[ExpectedException(typeof(ArgumentNullException))]
[PexGeneratedBy(typeof(when_account_transfer_occurs))]
public void overall_behavior_correctIAuthorizationServiceAccountAccountDouble_20080607_120018_002()
{
Account a0;
a0 = AccountFactory.Create(0);
AuthorizationService as0 = new AuthorizationService();
this.overall_behavior_correct((IAuthorizationService)as0, a0, (Account)null, 1);
}
Posted by
Colin Jack
at
6/07/2008
3
comments
Labels: Pex, Unit Testing
Apparently the issues I was having with Pex (ClrMonitorFail errors) were caused by its interaction with TypeMock. This doesn't shock me as having used TypeMock for a while I've learned that any time anything odd starts happening disabling TypeMock is a good idea.
So I disabled TypeMock and started playing with Pex, first impression is that it looks great but my second impression was that the IDE integration seemed a little flaky. My IDE actually crashed many times whilst using it but after a while I learned what to click and not click :)
Anyway I thought I'd start writing down the little that I've found out about Pex in case it is in any way useful to anyone.
First Feelings
I did notice a few interesting things when working with Pex, the first is that it seemed like it c lull you into a false sense of security.
Seeing a whole loading of auto-generated tests passing is great but I quickly began to notice that I could modify the code under test in inappropriate ways and my tests weren't failing. This wasn't Pex's fault though, I just hadn't been thorough enough in telling it what to expect and once I applied more PexAssume values and a few more assertions I definitely felt safer.
Fix It Or Allow It
I found that I was getting some useful tests generated even if I was quite vague:
[PexMethod]
[PexUseType(typeof(AuthorizationService))]
public void overall_behavior_correct(IAuthorizationService authorizationService,
Account source, Account destination, double amountToTransfer)
{
new AccountTransferService().Transfer(source, destination, amountToTransfer, authorizationService);
}
The tests Pex was generating were to do with null reference exceptions and invariants that the SUT was enforcing. Obviously initially the tests were failing so I had to tell Pex what I expected the SUT to do in each situation. I could do this using either the "Allow It" or "Fix It" options from the "Pex Results" panel.
If I chose "Fix It" then I would tend to get the following:
My IDE would then close down, gah. However if I persevered though it would update the test, for example:
[PexMethod]
[PexUseType(typeof(AuthorizationService))]
public void overall_behavior_correct(IAuthorizationService authorizationService,
Account source, Account destination, double amountToTransfer)
{
PexAssume.IsNotNull((object)source, "source");
PexAssume.IsTrue(source != destination, "source == destination");
new AccountTransferService().Transfer(source, destination, amountToTransfer, authorizationService);
}
When I then ran Pex for this method again it wouldn't generate a test that passed in null for source or that passed in source and destination as the same objects.
The alternative to "Fix It" is to select "Allow It" it, when I did that Pex would put this attribute in PexAssemblyInfo.cs
[assembly: PexAllowedExceptionFromAssembly(typeof(ArgumentException), "PexPlay")]
This seems a bit brute force though, I don't want to allow the exception across the entire assembly so I probably need to do a bit more research.
Decimals
One interesting thing that I noticed is that when I setup my methods to take in decimals I got no tests generated, but if I changed the inputs to be doubles I did. Not sure what that's all about but again I need to do some more research.
Mocking
Ignore the layout of this test, its a mess, but I do like the easy way I'm able to specify that I want to use a mock of the authorization service using the PexUseType attribute:
[PexMethod]
[PexUseType(typeof(MockAuthorizationService))]
public void transfers_correctly_between_accounts(IAuthorizationService authorizationService,
double intialInSource, double initialInDestination, double amountToTransfer)
{
PexAssume.IsNotNull(authorizationService);
PexAssume.IsFalse(amountToTransfer < 0);
PexAssume.IsTrue(intialInSource > amountToTransfer);
Account source = new Account(intialInSource);
Account destination = new Account(initialInDestination);
double fromSourceBefore = source.Balance;
double fromDestinationBefore = destination.Balance;
new AccountTransferService().Transfer(source, destination, amountToTransfer, authorizationService);
Assert.AreEqual(fromSourceBefore - amountToTransfer, source.Balance);
Assert.AreEqual(fromDestinationBefore + amountToTransfer, destination.Balance);
}
The mock service is in this form (see the PDF for more on this but I haven't truly had time to grok it yet):
[PexMock]
public class MockAuthorizationService : IAuthorizationService
{
public bool AllowTransfer(Account source, Account destination, double amountToTransfer)
{
var call = PexOracle.Call(this);
return call.ChooseResult<bool>();
}
}
When I run Pex over transfers_correctly_between_accounts it will actually correctly use an instance of MockAuthorizationService and will run a test where that service returns false, causing the transfer to fail as expected. Nice.
Posted by
Colin Jack
at
6/07/2008
3
comments
Labels: Pex, Unit Testing
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