Showing posts with label TDD. Show all posts
Showing posts with label TDD. Show all posts

Thursday, October 16, 2014

Todo: Add tests ...

I added this line in a README file for one application I'm writing now. Like I have done before many times. However, for the longest time I have written my tests first, maybe not TDD or even unit tests, but I write the test first. Most of the times.

But not this time. Because I was in a hurry and I didn't think that this application would be something we'd use.

And of course we ended up using it. And creates a financial record and prints a receipt. It's kinda of important that it's correct.

It just struck me:

  • how much harder it is to write the tests afterwards
  • how much I change in my production code, that wasn't in place, when I go through it and test it
  • how much more boring it is to write the tests afterward
  • how easy and tempting it is to "cheat" and not test the hard stuff
  • how hard the feeling "this is not done/safe/correct/complete" hits me in the face
  • how little satisfaction I get from completing a test. It's just like paying off an overdue bill. "Yes, I should have done this before. Now it's done". 
I'm not saying that You have to write your tests first. I'm just saying that to me it's: easier, safer, less boring, gives me better discipline and more rewarding. You do as you want. 

I will never write "TODO: Add tests..." again without remember these feelings. 

Friday, February 07, 2014

Marcus Node Bits: supertest is a nice way to test an api

Marcus Node Bits: Should is a nice way to do asserts

Friday, December 20, 2013

Nancy Fx - now you can read her too!

I fell in love with Nancy at first sight; so slick, minimalistic, testable and understandable, powerful and extendable when I need it. I later learned those features had a name; the SuperDuperHappyPath and I've been on it ever sense I first laid eyes on Nancy.

Christian Horsdal (one of the people that first showed me Nancy) had written a book on Nancy in the style of Nancy. This is a great companion to every Nancy-developer. I love the bundling in  recipes and how they are "graded" in from Simple through Intermediate to Advanced.

Monday, December 10, 2012

Have presentations - will travel

I have a couple of slow weeks before my next assignment starts for real, so as an early Christmas gift Aptitud and I thought that we could give away some presentations for free.

Please contact me on marcusoftnet at gmail or @marcusoftnet if you are interested in hearing any of the presentations below. No charge (saved any travel costs outside Stockholm... and the obligatory cup of strong, black coffee) and no strings attached.

[UPDATED] I have now booked my calendar to a suitable level (almost full). The response on this post was just overwhelming and I got 7 different gigs including a whole day at one company and a contact in Brasil (!). Might do this again. Longing to be bored again.

Wednesday, November 14, 2012

TDD for kids

I had the opportunity to do something exciting yesterday. I was invited by my good friend Tristessa to teach a class on programming for her 13-14-year olds. She teaches at the International School of the Stockholm Region and had introduced them to programming just a couple of weeks before I came.

Since the first time I learned TDD I've always thought that it's a bit like thinking like a child; challenging the code, come up with more examples, try to break/understand your code and just being curious. Also - when TDD works it feels much like doing a puzzle - the next piece just comes to you in a nice way, another kid-activity.
So I thought I'd try to teach them TDD during an hour and a half.

Tuesday, September 04, 2012

Getting Visual Studio 2012 Test Explorer to work with NUnit,xUnit and SpecFlow

Yes, it's this is another "hey this is a cool feature of Visual Studio 2012" post. If you know all about the new Test Explorer and how to get NUnit, xUnit and by association SpecFlow to work with it - you can stop reading here. For me it took awhile to get up and running.

I don't remember where I first read about it but I remember that I was happy to read that Visual Studio 2012 comes with a new Test Explorer. What's really cool about it is that it's no longer limited to just MsTest tests, but can run NUnit, xUnit ... you name it.

This means that my SpecFlow tests can be run from the new Test Explorer as well. You know, all SpecFlow actually does is translating the Gherkin lines you write into unit tests of your framework of choice. It should just work.

So they said...

Imagine my disappointment when the test explorer just reported "No unit tests found in solution" over and over again.

So after awhile I picked up that you (of course!) need to install adapters for the unit test frameworks you want to have the Test explorer to pick up.

That's quite easy. You go to Tools -> Extensions and Updates and search the Visual Studio Gallery (you'll find it under the Online-tab in the dialog) for NUnit, xUnit or whatever framework your using. What you are looking for are Test adapters for Visual Studio 2012. Like these:

When that is installed I was again happy to see that Visual Studio picks up my SpecFlow specifications and I can run them from the test explorer. 

But wait, there is more

When I started to use the Test Explorer I found a couple of nuggets in there too, for us SpecFlow-users:
  • Double clicking a test takes you too... The specification and not the generated test. Thank you very much mr Hidden pragma (#line hidden)
  • You can run only failed, or passed for that matter and even a shortcut for rerunning the last test run. It seems like TDD practices are getting a firm footing at Microsoft...


  • There is, from the Test menu, an option to rerun the tests on every build. So it's a bit like a poor mans MightyMoose and NCrunch test runners.
These small things made me happy and my productivity boost a bit again. Once I knew who to get it to run with the testframeworks I normally use. 

I like it!

Thursday, June 14, 2012

What BDD is all about

I got an email from a colleague a couple of weeks back. We were members of the same team for awhile this last autumn. He (and the rest of the team) are great programmers - way better than me. I had some difficulties to keep in step with them, but to some extent that had to do with F# being the language of choice. A first for me!

We had a lot of discussions about TDD and if it's feasible or pay off. This project made me realize that TDD done backwards (writing unit tests after the production code) is not only NOT TDD but also doesn't pay off.  But as I am dunked deeply in the BDD pool I suggested that we've take a look at that and get started that way. I never got through there...

So I was very happy when he wrote me an email with a link to an article that talk about doing BDD with SpecFlow and White. The question was simply; Is this how BDD is done?

This was a temptation that I couldn't resist... I thought I'll drop the answer in here too.

Friday, May 04, 2012

Applying the Switch framework to developers don’t want to write tests–part III

This is the last post in my series on how to motivate developers to write test for their code. Please read the first two posts to get some context (part 1 and part 2).

This post talks about the last part of the Switch Framework – Shape the path. This is all about making the change easier by helping our rider and elephant to get a smooth path to walk on as they change.

Applying the Switch framework to developers don’t want to write tests–part II

This is the second part (read the first part) of my trying to get inspiration from the Switch book on how to get developers to realize that we also need to take our responsibility for the quality to test. It not just the testing departments problem. As W. Edward Deming put it;

“Quality is everybody's responsibility”

Last time we took a look at the first principle – Direct the Rider. This time the turn has come to the elephant in the kitchen. The emotions and things that we cannot control by pure will power – it’s time to see if we can Motivate the Elephant.

Thursday, May 03, 2012

Applying the Switch framework to developers don’t want to write tests

Last week I attended the premier agile conference in Sweden, Agila Sverige. In one of the Open Space sessions we had a great discussion on why, still to this day, many developers don’t think writing test is important. Or at least boring and second grade job for a developer. The session was suggested by Ville Svärd who apparently has spent quite a lot of time on trying to convince developers that testing is important and also an important part of their job. So the whole session was just us sharing ideas and tips on how to help and convince developer to catch the testing-bug – it was aptly named “Testing is cool!”.

Yes, yes – you could argue that it’s simply just to hit them harder and tell them that “They must!”. But I don’t think that works particular well. At least it don’t stick. Around here I got to think about Switch and a blog post I wrote awhile back where I applied the Switch Framework to developers ignoring broken builds. Why not try that same trick again – I thought to myself. ‘¨

Friday, January 21, 2011

TDD and Scaffolding

During my ventures in to new Microsoft land I’ve stumbled on the concept of scaffolding (in the form of the excellent MvcScaffolding). The concept is well known in other frameworks and one of the eye-opener features of for example Ruby on Rails.

But as I started to use scaffolding I had to stop and think for a while on other values that I have come to hold in high respect such as TDD for example. The whole concept of driving out my code guided by test has completely changed the way I code. And my code!.

I don’t feel very good about myself, nowadays, if I have to write code without tests. But this scaffolded code is not code I have written. Should I write test for it? Before the code is generated or afterwards.

Since I couldn’t find to much about it I though I jot down some thoughts on the subject. I think that it’s something that will be used more and more in the Microsoft sphere.

Friday, November 05, 2010

Should & Substitute–two new great friends

Recently I’ve stumbled upon two great framework that greatly enhanced my test code.

Should I? Yes – you should!

First up is Should – which is a assertion framework that makes your assertions much more readable and easier to write. Here’s some code that shows off it’s capabilities:

    object obj = null;
obj.Should().Be.Null();

obj = new object();
obj.Should().Be.OfType(typeof(object));
obj.Should().Equal(obj);
obj.Should().Not.Be.Null();
obj.Should().Not.Be.SameAs(new object());
obj.Should().Not.Be.OfType<string>();
obj.Should().Not.Equal("foo");

"This String".Should().Contain("This");
"This String".Should().Not.Be.Empty();
"This String".Should().Not.Contain("foobar");

var list = new List<object>();
list.Should().Count.Zero();
list.Should().Not.Contain.Item(new object());

var item = new object();
list.Add(item);
list.Should().Not.Be.Empty();
list.Should().Contain.Item(item);


One really nice feature is that the framework isn’t tied to any testing framework but works nicely with any test framework.


Get me a substitute! Now!


The other framework is NSubstitute which is a mocking framework. I first got hooked when I read their intro:



Mock, stub, fake, spy, test double? Strict or loose? Nah, just substitute for the type you need!


I’m probably the only one (NOT!) who mess mock, stubs and fakes up except from just after I read a book on the subject. And really – who cares? I just want something to replace the real stuff for a while – let’s call it a substitute.


The syntax is also super-clean and easy going. Here’s the example from the NSubstitute site:

//Create:
var calculator = Substitute.For<ICalculator>();

//Set a return value:
calculator.Add(1, 2).Returns(3);
Assert.AreEqual(3, calculator.Add(1, 2));

//Check received calls:
calculator.Received().Add(1, Arg.Any<int>());
calculator.DidNotReceive().Add(2, 2);


Come together. Right now!


But the true power, I think, you get when combining these two together. Here’s an example from I did to show SpecFlow that uses both Should and NSubsitute:

[Given(@"the following features in the database:")]
public void GivenTheFollowingFeaturesInTheDatabase(Table table)
{
var features = table.CreateSet<Feature>().ToList();

var dbWrapperSubsitute = Substitute.For<IFeatureDBWrapper>();
dbWrapperSubsitute.AllNotDone().Returns(features);

ScenarioContext.Current.Set(dbWrapperSubsitute, DBWRAPPER_KEY);
}

[When(@"I navigate to the homepage")]
public void WhenINavigateToTheHomepage()
{
var featureDBWrapper = ScenarioContext.Current.Get<IFeatureDBWrapper>(DBWRAPPER_KEY);
var controller = new HomeController(featureDBWrapper);

var indexView = controller.Index() as ViewResult;

indexView.Should().Not.Be.Null();
indexView.ViewData.Model.Should().Not.Be.Null();
var features = (IList<Feature>)indexView.ViewData.Model;
features.Should().Not.Be.Null();

featureDBWrapper.Received().AllNotDone();

ScenarioContext.Current.Set(features, FEATURES_IN_VIEW_KEY);
}

[Then(@"I should see a view with the following features:")]
public void ThenIShouldSeeAViewWithTheFollowingFeatures(Table table)
{
var features = ScenarioContext.Current.Get<IList<Feature>>(FEATURES_IN_VIEW_KEY);

var expectedFeatures = table.CreateSet<Feature>();

foreach (var expectedFeature in expectedFeatures)
{
features.Should().Contain.Any( f => f.Name == expectedFeature.Name);
features.Should().Contain.Any( f => f.AssignedTo == expectedFeature.AssignedTo);
features.Should().Contain.Any( f => f.HoursWorked == expectedFeature.HoursWorked);
features.Should().Contain.Any( f => f.Status == expectedFeature.Status);
features.Should().Contain.Any( f => f.Size == expectedFeature.Size);
}
}


You can find the whole solution here.

Tuesday, September 07, 2010

Snippet for creating testmethod in VB.NET

I've already posted this snippet in C#, but as I from time to time need it in VB.NET I'll post that too. Here you go:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>TestMethod</Title>
            <Shortcut>tm</Shortcut>
            <Description>Code snippet for creating a testmethod</Description>
            <Author>Marcusoft (www.marcusoft.net)</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
                <SnippetType>SurroundsWith</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>methodName</ID>
                    <ToolTip>The name of the test</ToolTip>
                    <Default>methodName</Default>
                </Literal>
            </Declarations>          
            <Code Language="VB">
              <![CDATA[<TestMethod()> _
              Public Sub should_$methodName$()
        ' Arrange
       
        ' Act

        ' Assert
        Assert.Fail("Implement test!")
    End Sub]]>
            </Code> 
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Monday, February 01, 2010

SpecFlow: BDD .NET-style

As you could read in my latest post I have be a bit frustrated with TDD and where to start, lately. BDD is of course the answer to that. But I must say that the frameworks are available to the .NET crowd is a bit weird. Either you have some really funky syntax (hey Anders, a new colleague and great guy) or it’s build on top on other stuff and where hard to work with.

I simply cannot see myself introduce any ordinary programmers to any of that.

But here is something that looks more like it… a bit at least; SpecFlow. It’s also built with an eye too RSpec, Cucumber and Ruby but build in the style of .NET and C#.

Here is a (silent) screencast, something about syntax and workflow and some great resources.

From this it even looks that they support Swedish… Great work guys!

I’ll be sure to look into this a bit more. Later. New assignment today.

Thursday, January 28, 2010

ASP.NET MVC, StructureMap and … TDD?

I’ve been playing around a bit with ASP.NET MVC and StructureMap (an IOC container). It all looks very nice and works wonder. During this I ran into an excellent blog post by Elija Manor on wiring StructureMap and ASP.NET MVC together. Beware of the favicon-problem though.

Again – i use NHibernate and Fluent NHibernate which so much nicer than the XML-stuff. The critics to Fluent NHibernate says that you cannot reach all functionality from Fluent NHibernate, but here is an example on how to set specific properties in your configuration. Helped me through this example.

Also found some great code examples from the TekPub NHibnernate series here.

OK – I've added “TDD?” in the title. I love TDD and it’s my preferred way of doing code, but I have a problem (to quote a thinker). I think TDD doesn’t help my through the broader strokes of my application.

Where do I start? How do I use the test to know that it’s time to add an repository, or an IOC Container? Do I TDD the IOC-code?

I asked the Swedish ALT.NET group a question and got some great tips, mostly they pointed me to BDD and those ideas. I also liked the idea of the Walking skeleton.

But I’m still confused. Can TDD really help you to design a system from the bottom up, or top-down (BDD) for that matter? Will the design be improved by the TDD-design technique? I’m not sure.

For now, my thinking is that it’s better to create a very simple design (MVC + repositories + IOC) to get your “skeleton to walk”, maybe with a functional/integration test that verify the functionality.

With that foundation in place it becomes easier to add some meat to the bones (is this skeleton metaphor taken too far yet?) with the normal TDD techniques and patterns.

Wednesday, January 20, 2010

NUnit and the constraint based model

At the Elevate presentation yesterday I learned a lot about C#3/4 by Magnus Lidbom.

But as a side-effect I also picked up a nifty syntax for NUnit assertions. It’s called Constraint-based Assertion Model and has been around since NUnit 2.4. Which shows that I am a slow adopter… Sad.

OK – what’s the deal with it? It gives you a almost fluent interface to assertions. Here is an example on how to do a simple assertion in the old style:

And here is the same assertion in the Constraint-based version:

Now read it out loud; Assert… That … i … is equal to 10. Nice, isn’t it? I like that a lot.

Thursday, January 14, 2010

TDD and legacy code

I have been doing some presentations on TDD and one thing that always happen is that you get some tricky questions in the beginning of the presentation.

As you’re introducing a new concept it of course starts very small and easy but most people directly try to put into their context, their normal situation.

And let’s admit it – there not very often we start off in a void, aka. a green field project. No – it’s mostly brown field - there is always code that exists that needs to be handled. What’s worse – that code is not written to be tested – Not Designed for Testability.

I think this is a very interesting subject and it touches on other subjects that I’m interesting on surrounding why it’s worth “clean up your room” (as Uncle Bob would have put it…)

There’s a lot written on this subject, most notable and my next read, Michael Feathers Working Effectively with Legacy Code.

But from my good friend Calle Lindelöf I’ve got a tip for two great articles by David Laribee. Here you go, thank you Calle:

Tuesday, January 05, 2010

Trying Coding Dojo, Kata and Extreme OOP

In preparations for a presentation next week (which will go on for two days… brrr) I had my sights set on doing something about Extreme OOP or Object Calisthenics. I’m thinking of using that exercise to illustrate some OOP practices.

In the PDF-file for the Extreme OOP above you’ll find an excellent kata (the Commodore 64 kata) that will take you through all the rules of Object Calisthenics.

OK – but since I didn’t wanted to do that exercise all of my own I hooked up with two Avega colleagues (David Blomberg and Magnus Forberg, great guys!) and we did some kind of coding dojo.

The findings was quite surprising.

  • First – the rules of Object Calisthenics are not be followed when you do ordinary code. It’s simply an exercise to get you to think about OOP in a very structured fashion.
  • Secondly – the rules are very hard to follow… Very hard. We didn’t get quite there I felt.
  • Thirdly – the main take-away for me was that you learn so very much by doing pair programming and TDD together. It’s simply the best way to code in my opinion. The amount of information that is transported back and forth for each code line is immense. I almost don’t dare to do code on my own ;)
  • Fourth – just by sitting next to another person coding is a great learning experience. Shortcuts, patterns, tricks and structuring solutions – everything you can think of. And it sticks.

So – I still think the exercise was good – but it didn’t get to what I thought and I learned a lot of stuff that I didn’t thought either. Thank you guys.

Thursday, September 17, 2009

Reference work #3 – TDD by example

I have noticed that I’ve been reading some reference literature in the IT-department lately. I don’t know why but it’s a great way to get to know some of the giants that frequently is mentioned in current hot developer topics.

So after Patterns of Enterprise Application Architecture and Clean Code the time had come to Test-driven development: by example (my good –Google Books is almost scary).

This is was by far the funniest IT-book I ever read. I burst out laughing from time to other and found myself giggling through the whole thing. For example read this paragraph about the time when Kent Beck was young.

The book itself is centered around two example that take you through a variety of disciplines in TDD. And then mr Beck talks about patterns in TDD; design patterns, testing patterns and refactoring pattern.

Overall I felt that the book was more about the mindset that you should have towards and with TDD, than to “teach” the steps. Although the steps were thought along the way.

I almost read the whole thing from start to finnish in on go. Thank you mr Beck for a great experience and a great book.

Oh yeah – now I have Domain-driven design: tackling complexity in the heart of software on the table next to my bed. I am longing to read that one to. Reference work #4…