Moq – Mocking the same method call with multiple results

The Scenario

I have a loop in production code that has evolved into processing batches of records. I need to modify an existing unit test to accommodate mocking the same method call each time through the loop returning different results on each loop (as it would in production).

The Solution

Using Moq we can make use of a Queue and Dequeue result sets each time in the loop as follows:

for (var i = 0; i < loop; i++)

{

var jobsInBatch = BuildJobs(batches).ToList();

jobQueue.Enqueue(jobsInBatch);

jobQueue.AddRange(jobsInBatch);

}

_processor.Setup(m => m.GetAllJobs(batches)).Returns(() => jobQueue.Dequeue());

Accessing an internal class from an external assembly

I was working with a customer’s code base recently and I noticed a separate Unit test project was referencing an internal class in a different assembly. Initially, I expected a code smell and perhaps some kind of wrapper that was exposing an internal class some how. After doing a bit of digging and examining dependencies further with Resharper I drew a blank. How was this possible?

I then recalled there’s a way of specifying a referenced dll as trusted but couldn’t recall how to do this. A quick Google (and good old Stackoverflow) pointed me towards marking the referencing assembly as a “friend” via the AssemblyInfo.cs .

The full detail over at Stackoverflow

XTC Convention – September 15th-17th 2017, Swindon

I was fortunate enough to be one of the 100 or so lucky punters to get a ticket for the sold out XTC convention in Swindon and fortunate enough that my house move landed a couple of weeks later than this convention (despite Lammy ribbing me “We’ll end up moving that weekend and you’ll have to miss you’re beloved XTC”!).

I have to declare my hand early here and confess that I was very late to the XTC party, not really fully discovering them until the late 90s. Whilst I was merrily picking my way through their discography and discovering all the delights that it has to offer I was missing the demise of the band and didn’t really discover Apple Venus and Wasp Star until Messrs Partridge and Moulding had firmly shut the door for the last time at XTC towers. So I wasn’t going to let the convention pass me by. A ticket was purchased for less than £30 for a full weekend of XTC fun and before I knew it I was making my way down the M1 then flooring it (don’t do it kids!) on the M5 to meet with fellow XTC mates Owen and Jacquie for a curry then on to the Friday night events.





Friday night



Arriving at the venue we were warmly greeted by the organisers and what a great bunch of people they are. They welcomed everyone on the way in and gave us all a goody bag with programme of events, badges and the weekend pass (each one signed by Andy Partridge). We got seated then split into teams for the XTC quiz. I think I managed to get about 3 questions right out of about 30. They were really nerdy, more so than the Stranglers convention I’d attended a few years earlier. But it was all jolly good fun and that continued with a tribute band and an open mic session. Easing us in nicely for the weekend’s events.

Saturday



Fairly early start, fed and watered and ready to go we have a lot to get in today. Starting with a walking tour of Swindon and pointing out the various XTC landmarks. This was great and incredibly organised. A lot of prep had gone into this and it showed. At times I felt it would’ve made a great Radio 4 documentary, those quiet moments walking in between sites and the bit where a local cyclist passes by and goes “What are you lot doing?” “Oh we’re doing a guided walk” …”What?! of Swindon? This dump” (says the local!) …”Yeah it’s for a band who were based here”….”Oh XTC? Enjoy” and off she cycles. We continue taking in various band members houses (admired from a distance) , music stores the band would frequent and such like.





Back to the venue and there’s a raffle. I don’t win anything but it’s great watching people jumping up and selecting an XTC goody. Again it’s such great value I can’t imagine any of the organisors profited off this (not that was the intention) and they clearly spent a lot of time and effort and investment in raffle prizes, treats on the table and even champagne! to toast the Bumper Book of Fun book launch.









A bit later John Moorish takes us through a slideshow and the XTC early days story. Most enjoyable and entertaining. What follows is an XTC discussion with various long standing fanzine and XTC authors. Mark Fisher then launches his XTC Bumper Book of Fun we all raise a toast and it’s a fantastic collection of XTC fanzine editions and refreshed with interviews with comedians (what is it about comedians liking XTC?) and various other bits and pieces.

The venue now goes a bit silent. Messers Moulding and Chambers are en-route! They walk into the venue, everyone applauds, they smile and wave. There’s a lot of love in the room. A queue forms and you can get records signed and have a chat. I have a brief chat with both Colin and Terry. Terry is so down to earth, you wouldn’t think he was bashing the crap out of the drums on many of the pivotal XTC albums. Colin as well is charming. Top blokes.

The afternoon wraps up and we grab food and get back to the venue where we are treated to 4! tribute bands and they’re all fucking great. Such talented bastards! I sit at the back taking it all in and nodding along with a nice glass of Malbec. As witnessed in this youtube vid…


Sunday



There’s a walking tour of the Uffington White Horse. It looks great and initially I was up for this but knowing I’m moving house next Fri or the Fri after (it was the latter in the end) I decide to head back up t’ut North! to pack boxes. But it’s been a complete blast! Geniunely a great time was had by all. Thanks again to everyone involved who made it a weekend I won’t forget.

Here’s to the next one. Now if only we can convince Andy Partridge to get involved! 🙂

Here’s a little sneaky peek into the Bumper Book of Fun – well recommended…..











Moq Vs Rhino Mocks

Just some rough notes I made coming from a Moq framework and converting to Rhino Mocks:

Asserting a method call

ISomethingRepository mockedSomethingRepository = MockRepository.GenerateMock();

var person = new Person { name = “Bob” };

// Act
var something = new Something(mockedSomethingReporsitory);

// Assert
mockedSomethingRepository.AssertWasCalled(x => x.Save(person));

Asserting a property was set

As above but assert on the property….

mockedSomethingRepository.AssertWasCalled(x => x.WasPersonSaved = true);

Using a Stub to control program flow

Similar to Setup with Moq we’d use a Stub to return the desired flow i.e:

ISomethingRepository mockedSomethingRepository = MockRepository.GenerateMock();

mockedSomethingRepository.Stub(x => x.ValidatePerson(Arg.Is.Anything)).Return(true));

Using a Stub to return the desired set on a property

ISomethingRepository mockedSomethingRepository = MockRepository.GenerateMock();

mockedSomethingRepository.Stub(x => x.IsValid).Return(true));

You can use GenerateStub here but the above setup for the stub keeps things syntactically the same in all mock setup instances.

Using Constraints to assert a method call with specific properties

In the first example we simply checked that a method was called. If we wanted to check the method was called passing in an object with specific properties we would do the following:

var personId = 23;
mockedSomethingRepository.AssertWasCalled(x => x.Save(Arg.Matches(x => x.Id == personId));

Hugh Cornwell – Louth Town Hall 1st November 2017

Just collected me thoughts after a mini break part of which took in Hugh at Louth.

I’m pretty familiar with Louth as my wife grew up there and has family there. I’m usually there 4 or 5 times a year. It’s a pretty weird place. Pleasant enough but a bit of a bitch to get to and seems like a place famous people retreat to. You can often see Robert Wyatt drinking coffee in the town square, Barbara Dixon at the Co-op and even Dave Formula in the Brown Cow. Like I say, pretty weird.

Incidentally, Dave Formula promoted a blistering British Sea Power gig at Louth Town hall in the Summer a couple of years back and this is where I return to tonight to see Mr Cornwell. I’m fearing a handful of punters for a dark midweek gig in the middle of no where but as we walk up the stairs and enter the main hall I’m pleasantly surprised to see a 3 quarter full Town Hall. This fills up to almost no seats in the house by the time Hugh enters the stage.



It’s an interesting set. The first half consisting of Hugh’s solo material some of which he’s not played for a few years. Couple of audience members behind me talk throughout until it becomes unbearable “Paul….Paul!!” shouts one pissed up lass to some hippy looking bloke. Myself and a couple near me tell him to pipe down. He gets the message “Fuck this I’m off for a cig” 🙄 He gets up and duly fucks off. A small blemish on an otherwise great first half. I’ve my wife’s family with me who’ve not really heard much Stranglers stuff before let alone Hugh and they’re enjoying it.

An hour later Hugh reappears to give the crowd a blast from the past. It’s a strong set, the sound is perfect (possibly the best I’ve heard him). His guitar and vocals warm and rich. Fantastic effort to all concerned and the man himself. Highlights for me were Henry Moore (good to hear it again), Ships That Pass in the Night (which Hugh announces as like “playing a game of chess”), Big In America (sounding big!). To be honest it’s all good. Can’t wait for the next one which I believe will be around May time. See you then.