Wednesday 20 August 2014

a gotcha with nunit

Was writing a unit test with nunit the other day which went something like :



[Test]
[ExpectedException(typeof(JobExecutionException))]
public void Failure_To_Get_Companies_Sends_Message_And_Logs()
{
   var mockBillingService = new Mock<IBillingService>();
   var mockCompanyService = new Mock<ICompanyService>();
   var mockLogger = new Mock<ILog>();
   var mockJobExectionContext = new Mock<IJobExecutionContext>();

   mockCompanyService.Setup(m => m.CompaniesToBeBilled).Throws(new Exception("problem getting the customers"));
           
   var job = new CustomerBillingJob(mockCompanyService.Object, mockBillingService.Object, mockLogger.Object);
           
    job.Execute(mockJobExectionContext.Object);
    mockLogger.Verify(m => m.Fatal("whoops", It.IsAny<Exception>()), Times.AtLeastOnce());
}

A subtle thing to be wary of is the verify call at the end, we seem to get funny behaviour when we use expected exception in our test and the call to verify seems to get ignored, i'm assuming that all nunit cares about is the fact that the test did throw the expected exception.

I have started rearranging the test so the call to execute is wrapped with a try catch and only handles the exception type you are expecting and does an assertion on that exception being generated.  It is also too easy to put at the top that you expect an exception of type exception too meaning you are not really testing the actual exception type you want to test.

hope that helps.

Thursday 6 March 2014

Autofac DI on action filters

Trying to inject a dependency on an action filter in MVC with autofac the other day, property injection seems to be the order of the day. So here's how to do it:

Here's the filter :

public class MyFilter: FilterAttribute, IAuthorizationFilter
{
       public Dependency MyDependency { get;set;}
}

Autofac registrations:

var builder = new ContainerBuilder();
builder.RegisterFilterProvider();
builder.Register<Dependency>(c => new MyConcreteDependency());
builder.RegisterType<MyFilter>().PropertiesAutowired();

note the RegisterFilterProvider line very important.....

Shazaammm !

Friday 31 January 2014

stubbing awkward jquery calls with sinon.js

We had an awkward bit of code at work the other day that called a third party control  like so:

function myObject(jsSelector) {
    return $(jsSelector).thirdpartycall({
            propertya: valuea,
            propertyb: valueb
    });
};



so if we want to test myObject, we are now stuck with the unfortunate jquery call inside.  not to worry, sinon.js to the rescue.  first i need to create a fake return object from that javascript call:

 var fakeResult = {
        propertya,
        propertyb,
        thirdpartycall: function (values) {
            this.propertya = values.propertya;
            this.propertyb = values.propertyb;
            return true;
        }
    };

what i do next is to stub jquery, and on using the selector it returns our fake object... yep how cool is that !
make sure when you write your test you wrap it like so (i had some fun with other tests failing after this as I had stubbed jquery permanently !!!)

it("should do something....", sinon.test(function () {

}));

then add the code:

it("should do something....", sinon.test(function () {
    $ = this.stub();
    $.withArgs('#myselector').returns(fakeResult);
}));
           
so now, if we call our object:

myObject('#myselector');

we then check fakeResult and the properties have been set.
Super awesome.



Wednesday 13 November 2013

Form submissions in IE8 not working? check the buttons....

So for those of us who still have to put up with IE8 (Personally, i'd rather shoot myself in the face than have to deal with this nonsense) and your form submissions arn't working, check this little beauty:

<form>
      my form controls.....
      <button type="submit">mysubmitbutton and its icons</button>
</form>

click the submit button in IE 8 and no worky.... reason being is IE8 needs an input tag of type submit so if you find this, try changing your button to an input instead or at least putting a hidden input tag in there.

Joy !


Wednesday 23 October 2013

Quick guide to debugging javascript with jasmine and Resharper 8

Hi everyone,

just to make our development lives a bit easier in javascript, i wanted to debug a jasmine test the other day and did a bit of stack overflowing and managed to get it working lovely, so here's the skinny :

Resharper 8 is really cool and comes with a whole host of functions, if you haven't already, check out the extension manager is so choc full of goodies e.g. angular plugins, nunit stuff, it made me cry.....

Anways, on with the show.  If you haven't already you will need to enable the jasmine support in the resharper menu :


Once done, we can get to writing our jasmine test, here's an example:

/// <reference path="../../BCAResearch/Scripts/jquery-1.7.1.js" />
/// <reference path="../../BCAResearch/Scripts/app/chart/ChartDataFunctions.js" />

describe("mytestsuite", function() {

    describe("When doingsomething", function() {

        it("It should do this", function() {

                jasmine.getEnv().currentRunner_.finishCallback = function () { };
            
            var dummySeriesCollection = new Array();
            var dummyseries = { series: 'theseries' };
            dummySeriesCollection.push(dummyseries);
            dummySeriesCollection.push(dummyseries);
            dummySeriesCollection.push(dummyseries);

            var panel1 = { SeriesCollection: dummySeriesCollection };
            chartData.Panels.push(panel1);

            var dummySeriesCollection2 = new Array();
            dummySeriesCollection2.push(dummyseries);
            dummySeriesCollection2.push(dummyseries);

            var panel2 = { SeriesCollection: dummySeriesCollection2 };
            chartData.Panels.push(panel2);

            expect(ChartDataFunctions.MaxNumberOfSeries(chartData)).toEqual(3);
        });
    });
});

notice the call to the jasmine.getEnv, this tells the call back never to happen leaving the connection open to resharper.

what we can do then is open up our favourite browser debugging tools, put a break point on our code (which is called tests.js) then hit F5 and presto ! debugging your test.

makes me smile....


Wednesday 25 September 2013

Knockout keywords in IE8

So, we have a user base that is a majority share of IE8 users (i know, its depressing) and we are  suffering from a binding issue which turns out to be a knockout problem (well not a knockout problem, an IE8 being lame problem)

so if you are using knockout and IE8 and see a parsing issue with a knockout template e.g.

<tr data-bind="template: { name:'dataset-row-template', if: options.length > 0 }">

The offending bit is marked, change to 'if' and all should be happy.

Thursday 4 July 2013

Beware the eyes of March (and missing event.PreventDefault)

Just a quick tip, I recently had a click event on an anchor tag and a get that loaded in some content when clicked like so:

$('#myid').click(function() {
     $.get('mvcurlhere', function (data) {
          //load my div here
      })
});

if you find yourself scratching your head when your MVC call using ajax and $.get seems not to be returning its because you didn't stop the original anchor from calling back, once more if your anchor tag has a # as the href which we all do from time to time, you will get the same page back with a # appended to the url and all sorts of great stuff starts happening my friends (especially with Chrome)

Solution ? remember the JQuery event.preventDefault call :

$('#myid').click(function(event) {

     event.preventDefault();    

     $.get('mvcurlhere', function (data) {
          //load my div here
      })
});

Happy days.....