Testing

Why I’m doing unit testing

Wednesday, 23 September 2009

Posted by Sébastien Lachance with Comments (0)

To be honest, I believe that we have reached a point where we can’t allow ourselves to deliver untested software. I lived through a lot of maintenance work and debugging that were so time consuming that It took more time to debug than it took to actually develop. And it’s for that reason that I believe that unit tests are essentials and should belong to every developer toolbox.

Easy to get started

It’s actually not so hard to learn and a lot of resources already exists to get you started rapidly (Roy Osherove and his book are a must).

Unit test and design

I also believe that unit tests have a strong positive impact to the design of the code. Doing correctly, TDD (test-driven-design or test-driven development) is a powerful tool. I’m talking with experience here and it’s very impressive. I worked on two almost identical project and one was driven by test and the other was not. The quality of the design was much much better on the project that was test driven than the other one. But what was way more impressive was the number of changes made to the structure of the project. Code with tests has evolved tremendously and untested code had a static structure that stayed the same over the course of it’s development.

Unit test as a learning tool

And a great one it is. I recently had to create regular expression to find email in some large text file. Instead of rapidly hitting google for a rapid solution, I created a class library, added the nUnit framework and started writing tests. This way, I could test assumptions and learn some aspect of writing regular expressions. I learned a lot.

I can’t believe!

Today, I can’t believe myself when I see a method that contains logical code, and no tests. Tests are so easy to do (when you actually know how to do them) that it’s almost a shame to forget about them.

My answer

And here is my answer to the “we don’t do test because our organization don’t want to” argument : Don’t tell them. You are responsible for the quality of your code and it’s very unprofessional to leave code go in production that you knew would have been much better and feel more confident if it was tested. I believe the advantages outweigh the disadvantages in this particular case.

This is my point of view. 



Resetting TeamCity Password

Wednesday, 12 August 2009

Posted by Sébastien Lachance with Comments (0)

I’m using TeamCity Version 4.5.3 (build 9035) and today I really couldn’t remember my password. After searching for a while and trying various solutions, I have found this one working perfectly.

Solution :

Open a command prompt and go to <installation folder>\webapps\ROOT\WEB-INF\lib folder. Now type the following :

..\..\..\..\jre\bin\java.exe -cp server.jar; common-api.jar;commons-codec-1.3.jar;util.jar;hsqldb.jar ChangePassword username newpassword

Notes : Change your Java.exe path accordingly. In this case I use the one located in the TeamCity folder.



NDepend - Small review

Monday, 10 August 2009

Posted by Sébastien Lachance with Comments (0)

I have been using NDepend on various project I am working on and there is so much to say that I can’t wait to do a full review because I will make you wait too long. I got a free license and wanted you to know what the tool can do and what were my impression.

First of all NDepend is a tool that analyse your code. It’s huge! Definitely not a tool you can learn in an hour or two. Simply give the tool a solution or project file and start analyzing. You are first presented with a a complete map of your application. By default it shows all your code sorted by the number of lines but you can quickly switch by different kinds of metrics (LOC, Cyclomatic Complexity, IL instructions, Efferent coupling, etc.).

ndependcomplete

The best part is that you can write query against your code. This feature is called CQL (custom query language). Need to know which method have more than 200 lines of code? No problem. Really. It looks like SQL and is easy to write (I haven’t written any yet, but I’m sure it will prove useful later).

Take a look at this :

// <Name>Methods with too many local variables (NbVariables)</Name>
WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE NbVariables > 15 ORDER BY NbVariables DESC

Out of the box, NDepend provide around 200 CQL queries. It has queries to find unused or dead code, find which method are not test covered, naming convention not respected, types with too many methods, ect. Each rules has a short description on what it does and even provide links to more complete documentation if needed. It also has intellisence as if this wasn’t enough.

A cool feature is the dependency matrix. It’s easy to see where is your dependencies.

ndependmatrix

The tools itself is beautiful, it make us want to play more with it (it does not use WPF, but it appears to).

A lot of features that I haven’t used yet are :

  • Compare assemblies
  • Code Coverage
  • Writing complex  custom rules

I recently came across this post entry by Patrick Smacchia (creator of NDepend) that used the tools to spot bugs in an existing code base (http://codebetter.com/blogs/patricksmacchia/archive/2009/06/21/agile-behavior-nurture-knowledge-database.aspx). I don’t know why but this has really struck me and kept it in my favourites. I could write custom query to spot bad practices and potential bugs.

But there is a downside. On a project I worked last year. Every query that has been executed had a warning on it, almost every single one. That’s sad. I almost cried. But I’m fine now. NDepend will help me.

There is so much to say, that it’s almost impossible to cover it all in one single post. I’ll continue to use it and post any relevant information and features that I really enjoyed in the next couple of weeks.



Great unit tests review by Roy Osherove

Monday, 23 March 2009

Posted by Sébastien Lachance with Comments (0)

I watched the review of the unit tests of the ASP.NET MVC framework done by Roy Osherove and it was interesting. It’s great to have someone going through unit tests and explaining what they done right or wrong.

Here is some points he made in the review:

  • No dynamic values in assert.
  • Empty string tests.
  • Emphasis on readability.
  • Multiple assert on one test is bad.
  • Only one mock object per test.
  • Verify only what you need to.
  • Mocks that should be stubs.

Watch it yourself on the Roy Osherove blog.



How to test if someone subscribed to an event with Rhino Mocks

Monday, 10 November 2008

Posted by Sébastien Lachance with Comments (0)

Very common scenario. There is probably a better way to do this, but this one get the job done.

var mockedView = MockRepository.GenerateMock<ICustomerView>();
mockedView.Expect(v=>v.Save += null).IgnoreArguments();
mockedView.Expect(v=>v.Delete += null).IgnoreArguments();
mockedView.Expect(v=>v.Load += null).IgnoreArguments();
new CustomerPresenter(mockedView); //Subscribtion to events 
mockedView.VerifyAllExpectations();


Web.Config to App.Config and Resharper's TestRunner

Friday, 07 November 2008

Posted by Sébastien Lachance with Comments (0)

If you are using the Resharper's TestRunner and have put your tests directly inside your web application assembly, you may ran across the configuration file issue. That is, that you create a test that, in a way or another, will try to access your application configuration file. The problem is that the Web.Config file is not copied to the bin folder and is not renamed following the configuration file convention of anything else that is not a web application. To ensure that you will have access, you can add a post-build event in Visual Studio that will copy the Web.Config to the bin folder with an appropriate name (applicationname.dll.config).

Right-Click on the project => Properties => Build Events and paste this :

copy /Y "$(ProjectDir)Web.config" "$(TargetDir)$(TargetFileName).config

BuildEvents



My TeamCity testimonial

Wednesday, 29 October 2008

Posted by Sébastien Lachance with Comments (0)

Some months ago, someone from Jetbrains asked me if they could use a comment I made on my TeamCity blog post (the one I demonstrate how to get TeamCity up and running) on their testimonials page.

My testimonial. However, I am not working anymore for bxsystems but for a great local company where I currently live. I think there is a lot of potential there.

I still believe TeamCity is an impressive product and I am waiting for version 4 that will be out soon.



Ohhh, that's why I should make a TestRepository...

Wednesday, 14 May 2008

Posted by Sébastien Lachance with Comments (0)

Listening to the last screencast of Rob Conery (MVC Storefront) made me realize something that I haven't really understood before.

Suppose you have the interface of a repository, let's say IEntryRepository. Then you have the actual SqlEntryRepository and TestEntryRepository. When I am doing TDD, I am testing the TestEntryRepository. But it will not be used in production. Why bothering with testing it then?

Because TDD is a design process. Even if I am testing my code, I am also designing it. The SqlEntryRepository will benefits from the actual design of the repository we use for testing.

 



Mocking the HttpContext in ASP.NET MVC

Thursday, 08 May 2008

Posted by Sébastien Lachance with Comments (0)

I just got a hard time figuring how I could be mocking the HttpContext so that I would be able to mock HttpRequest. But once you understand the principle, it is fairly easy.

First thing we need to know is that the HttpContext is held inside a ControllerContext object. Once we have instantiated one, we can then put it inside our controller.

controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
 
Where mockedHttpContext is your mocked HttpContextBase object.
 
Inside the HttpContextBase object reside a lot of useful stuff that can replace with our mocks. By example, the HttpRequest, HttpServer, HttpApplication, etc, are all contained inside. So, getting familiar with this basic knowledge is a must to do testing usefully.
 
Next post : Mocking HttpRequest.Form to return what we want.


Testing controllers in ASP.NET MVC aka ActionResult

Tuesday, 06 May 2008

Posted by Sébastien Lachance with Comments (0)

I haven't really done any testing in ASP.NET MVC until now. I started the development of a more serious application and decided to do it TDD. My first test was to make sure the Index action render the Index view. So as an informed developer, I started reading some blog posts to discover that in order to test a controller you need to mock a lot of things. I followed the screencast of Scott Hanselman and implemented his MvcMockHelper. It didn't worked. The ViewContext on the view engine remained null, resulting in an NullReferenceException. I downloaded the source of the last build to see for myself what was wrong. Surely I don't understand, because nowhere in the source they are setting the ViewContext on the ViewEngine. They just fill a RenderViewResult object and return it back.

This is how I figured out how we can now test controllers. With the new Interim build of the 04/16, we don't have to mock the HttpContext, HttpRequest and so on anymore. No need to do a fake view engine and no more mocking needed to test the RenderView method.

[Test]
public void Index_Should_Set_The_Index_View()
{
EntryController controller = new EntryController();
var result = (RenderViewResult)controller.Index();

Assert.That(result.ViewName, Is.EqualTo("Index"));
}

So if you have any other operations (RedirectToAction and Redirect for example), it will return an object of type ActionResult that you can cast to the appropriate inheritor (RenderViewResult, ActionRedirectResult, HttpRedirectResult) to get a lot of information that you would have to retrieve manually with a mock.

I really like the simplicity of it and can't wait to see more improvement. This is an immense opportunity to learn a great deal of different things.