Combining Moq callbacks with NUnit

5/05/2010

I didn't want to write too much articles about unit testing, I meant something more development-related thing.
Few months ago two new experienced members joined the team, they shook up the group immediately. Everybody disliked the mocking framework we used that time, so they proposed to use a new one. Now we write the new tests with Moq, the old tests are still using NMock2.
This short post is intended to show two different ways to check the behavior of one method with Moq.
The example will be very simple. Imagine that you have no return value, which you can use for expectation, so you want to verify if your tested method calls your mocked dependency with the expected parameters.


I will use the draft code below in the examples.


As you can see we have the layers here, the BusinessLayer is calling the DataLayer (I omitted the concrete implementation ) after initializing an instance of the Account class.

If the signature of your tested method contains only primitive types your job is very straightforward:



But if you want to pass a more complitaced object instead of primitives, probably you want to verify only some properties, not whole object.



In the first implementation of the test we expect that the SaveAccount method of the DataLayer is called with an instance of the Account class. In the same line there is the second lambda expression, which verifies that the instance of Account class has the expected property values.
This one is fine and works... but only if the SUT (SaveAccount method) will be called every time with the correct parameter. If the test fails, it fails a very bad way:
"Test method TestProject1.BusinessLayerTest.CreateAccount_WithPrivateAccount_VerifyCreatesPrivateAccount threw exception: Moq.MockException: IDataLayer.SaveAccount(MoqCallback.Account) invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup."


This is a typical situation when TDD yields profit for us. The failing test shows that we have some functionaly covered with a testcase and after an inaccurate modification the our new test will help us to find the bug.

But does the error message above really help us to find the problem? If this error is displayed to somebody else, he/she would say "WTF?". Of course this means he/she will have to put a breakpoint in the test and check what's going on. Troubleshooting is less time consuming if the method name and error message of the test are descriptive. In our case the method name is OK (we understand what the method should test), but it's hard to spell out what is wrong: the test code or the SUT.

To generate useful error description, you can combine Moq callbacks and NUnit (or your favourite framework) assertion API. According to the documentation the definition of the mock callback is the following: "Specifies a callback to invoke when the method is called that receives the original arguments."
We need exacly this, the original arguments of the called method. Most of the tutorials are writing this argument to the console....what a waste!

Let's change the Setup of the mock to verify only the type of the passed parameter and define a Callback which checks the expected property with your assertion API.



In this example we verified only one property, I recommend to extract the multiple assertions to a new method and call it from the Callback.

This is not rocket science. You can find the Callback feature of the mocks in the Moq QuickStart or with Visual Studio IntelliSense. I checked few basic Moq tutorials, but I haven't found this practice there.

Ohh, I almost forgot the main point...the error message of the failing test:
Assert.AreEqual failed. Expected:<Private>. Actual:<Enterprise>.
This is generated by Visual Studio assertion API, but the NUnit one will look something similar.

Read full article: Combining Moq callbacks with NUnit


1 comments:

Assign TFS task to check-in

11/19/2009

Microsoft Team Foundation Server is a very flexible system, different software companies are using it in a different way. Some of them are using only as a source control, some of them are integrating it with other external applications to take advantage of the flexibility.


This article won't provide you any new information, if you use TFS to bug and workitem tracking, but I want to motivate companies who are using TFS only as a code repository.


We have been working on a complex distributed application in last 12-13 months, the current team consists of 17 members including the testers.



There are some factors, which make the development process more complicated:

  1. in the past we had temporary workarounds, where the underlying code was removed 1-2 months later

  2. we had to modify the temporary workaround in production without uploading the code under development

  3. sometimes some team members are working on a feature, which requires more iteration

  4. we are doing code-review session

  5. we like refactoring the code after the code-reviews

  6. the testing department validates the application both in the internal and external environments

  7. packages created by the release manager are uploaded to different environments at different time

Read more, if you are interested how we manage the bugfixes and the implementation of new features with TFS.




The beginning was very easy, because we had less testing environments (there was only one internal one), because the product wasn't released. The integration process to this testing environment was still very slow and painful, because I had more paralell tasks and bugfixes.


To make my own work easier I began to assign my code check-in sets to the related work item (feature or bug). At the next integration I benefited from my new habit.


After many iterations I can honestly say:
Assigning work item to check-ins in Team Foundation Server helps us to speed up the integration in case of new developments or bugfixes.


Probably you have already realized some options in the Check-in panel. After you filled-in the Comment field, pressed the Check In button.


Assign task to check-in set in TFS


To help the continuous integration, we could assign the check-in to the related work item. To do this, you have to choose the Work items button on the left.
Assign TFS work item to check-in



You can choose the query to find the work item.
Assign TFS work item to check-in



Check the bug or work item:
Assign TFS work item to check-in



After selecting the checkbox, you will see the last column filled by “Associate” Check-in action.
If you followed the instructions, you only have to press the Check-in button.
To benefit from this activity, open your work item and navigate to links tab:
Assign TFS work item to check-in


After this, you will see the check-ins, where you can find the affected files and changes.



This solution is more advanced than typing only the work item ID to the comment field. Right after I was led to this conclusion I shared my experience with the team. Since a few months it's mandatory to assign the related task to all check-in sets, and the Release Manager configured the Check-in Policy to enforce fulfilling this rule.


Read full article: Assign TFS task to check-in


1 comments:

Refactoring SQL stored procedures

9/27/2009

I'm back after a couple of months... I've got a good reason to stop blogging for a while: I live too close to Costa Brava and to the mountains...paradise of motorbike riders.



Few months ago we improved the code quality of SQL stored procedures in our product. As the team is quite well-experienced there was no problem with the performance or the code quality of the queries if you opened one SP at a time. There was a time period when the team was separated and the communication wasn't sufficient, and there were a lot of stored procedures querying the same set of data but with different restrictions (WHERE statements). We had some time between two sprints and decided to start a pair programming session and make the procedures more clear.



Normally you design the database layer and all your queries before you develop them, but you can have difficulties here, if you don't know all the details of the specification at the beginning (or you have undocumented code from ex-colleagues).



If I have to touch a part of object-oriented compiled code I don't like or I have to reuse some bits, I apply some refactoring. This motivated me to come up with the following idea: apply refactoring patterns on the SQL code. Sounds crazy because we have no database IDE which supports the following requirements:



  • Go to definition

  • Find all references (View dependencies feature is not 100%)


This is a very boring manual process, you have to open the definition of all your DB objects (the dependency analysis gives some help).


The most boring pattern was the Reorder parameters (we had to modify the caller application), but we achieved to have a standard public interface.

After this step nobody call the SPs with incorrect parameters or incorrect parameter order.



The biggest fun and most interesting was the Extract Method pattern. I liked it! David (he was my pair developer) has a lot of experience in DB optimalization, it was great to discuss the pros and cons of extracting the SELECTs to a veiw or to UDF. Extracting the SELECTs to a view and apply the restrictions with UDF made the index creation much easier.



No matter what kind of language or technology you use, I recommend you to take a look at refactoring patterns, but don't forget: refactoring process assumes that you have unit tested codebase. Before starting the modifications you should consider using TSQLUnit.


Read full article: Refactoring SQL stored procedures


0 comments:

Windows7 for development

5/05/2009

After the public release of Windows7 Beta I decided to take part of the beta program and try the new OS for development at home. I upgraded to Windows7 that time and I had very positive experience.


Windows7 for development


As today is the day of public release of Windows7 Release Candidate, I'm just downloading the new version and I'm anxious to test this as well. I do only hobby-development at home to try new technologies and development tricks, but I had no problem running Visual Studio 2008 on Windows7 Beta. It was a surprise from a Beta product, so I'm interested in how the RC runs.

This laptop is 3-year-old, but performs much faster with W7 than XP.

Come on, download Windows7 now!

Read full article: Windows7 for development


0 comments:

Centralized exception handling and logging using PostSharp

4/26/2009

This is a quick tutorial to implement a .NET application/service facade with exception handling, without writing unnecessary, repeated try/catch blocks and logging mechanism. For more details and goals, please read my article about Centralized exception handling and logging in .NET by AOP.

You can implement almost the same with Spring.NET framework, if you want to read how, read my previous article.

PostSharp Laos is a compile-time AOP tool, after you have installed it, it will be automatically registered in the compilation process. No matter if you use Visual Studio or MSBuild, PostSharp modifies the compilation result (the assembly) without any manual configuration.
Don't forget to install PostSharp to each developer's workstation and to your build and contignous integration servers. Don't worry, it isn't necessary to install it to production environment, because PostSharp is a compile-time framework.


You can open my solution in Visual Studio 2008, it's in the same file, like the facade implementation using Spring.NET. I hope it makes comparison easier for you.

If you want to follow the tutorial, create a C# class library project (CodeRecycling.ServiceFacade) for your code and a test project (CodeRecycling.ServiceTest) for the unit tests.

To use the aspect-oriented features of PostSharp, you have to add two references: PostSharp.Laos.dll and PostSharp.Public.dll.

I added a new class called PostSharpHandledFacade. The architecture is the same like in my previous post: this facade calls the lower layer: BusinessLogic. We use the same BusinessLogic class and IBusinessLogic interface, the only change is in the facade.

I still don't want to create client application of the facade, so I simulate it with Unit Test. This is easier and helps to evangelize the TDD approach :)
I created a separate class in the CodeRecycling.ServiceTest project to test the the new facade. I call it PostSharpHandledFacadeTest.


We use the same DummyBusinessLogic fake BL class to simulate exceptions in the called layer without touching the production code. This is why I used constructor dependency injection in the SetUp() method.

You can compare this test with the Spring.NET one, the only difference is in the facade type. This was the reason why I created a base testclass in the first version of the project. But I removed the test-inheritance pattern from the project and separated the tests of the two facades to have a more clear demonstration in the two articles.

The facade class is missing, so we have to create one.



If you added this code snippet, and the classes from my previous article, you can compile. But you get red bar, because the fake business logic throws an exception with NotImplementedException type, instead of MyServiceException.

This is what we want to solve with PostSharp: we want to wrap the original exception to MyServiceException and do some logging.
Your custom exception type is ready if you finished the Spring.NET tutorial.

We can easily achieve this in a custom aspect which inherits from the OnExceptionAspect.



I hope you are able to compile, but I'm sure your tests are red, because we have the implementation for automatic exception wrapping and logging, but we missed the weaving. We have to attach our aspect to the facade. As you can reacognize, we have the "Attribute" expression in the name of the class...yes this will be attribute of the facade class.

You should add the PostSharpErrorHandler attribute to the PostSharpHandledFacade and you will be ready. The final facade implementation will look like this one:



Now it's green! Well done, you implemented automatic error logging, you have clear code, without unwanted try-catch blocks in each method. It's nice, elegant, Object-Oriented and easy to maintain. But if you want to be realy pro, you can write a behavior-test for logging.

Next step is to fine-tune the attribute with the named parameters (AspectPriority and AttributeTargets), this will specific to your application.

Read full article: Centralized exception handling and logging using PostSharp


1 comments:

Centralized exception handling and logging using Spring.NET

4/19/2009

This is a quick tutorial to implement a .NET application/service facade with exception handling, without writing unnecessary, repeated try/catch blocks and logging mechanism. For more details and goals, please read my article about Centralized exception handling and logging in .NET by AOP.

In this article I show you a step-by-step centralized exception handling and logging tutorial with Spring.NET, next week I submit a post about how to do the same with PostSharp.


The first step, isn't a surprise, you have to download Spring.NET Framework.

It's time to open Visual Studio 2008. You can use 2005 as well, but my sample code can be opened by 2008.

I created a C# class library project (CodeRecycling.ServiceFacade) for my code and a test project (CodeRecycling.ServiceTest) for my unit tests.

Spring.NET has a lot of features, we will use only the Aspect-oriented module, so in CodeRecycling.ServiceFacade project we add a reference to Spring.Aop.dll.

I added a new class called SpringHandledFacade, imagine this contains all the methods called by client applications. As it is only a facade, it calls the lower layers. I added the BusinessLogic class for this reason.
The BusinessLogic implements the IBusinessLogic interface. This interface is necessary because of the Dependency Injection. I use the Dependency Injection Pattern to avoid writing real business logic implementation and make the application more testable (I will inject a fake business logic here later). The interface has one method: GetNecessaryData() - has no meaning, but will be perfect for us (in the other hand this a tribute to Molino, my ex-colleague).

Let's go to the test project:
SpringHandledFacadeTest will contain the unit tests to perform assertions on the facade.

I added an other class called DummyBusinessLogic, I will use this as a test double.



We haven't done any error logging or exception handling, we don't use Spring.NET by the moment. I will apply the test-driven approach and specify our requirement by this unit test.



So we set the fake BL to the facade (which throws a NotImplementedException), and we expect a custom MyServiceExpcetion type. It's an exception-handling principle to wrap unhandled exceptions to a custom type.
You return more detailed or more generic exception in your custom exception type (this depends on your service consumers and your needs), I just inherited from ApplicationException and used a simple constuctor chaining.

After implementing your own Exception type, the project will be still unable to be compiled, because you don't have the constructor of the facede and the facade lacks of the GetNecessaryData() implementation.



After adding your code to the facade class, you can compile, but your unit test will be red. No problem this was our goal. Remember the TDD mantra: Red-Green-Refactor.

The next step is to generate a proxy for Spring.NET and attach the exception handling to it. I coudn't find a good solution to check exceptions directly in the facade, so I generaty a proxy for my BL, because the facade only calls the BL. In the other hand, I was able to define the advice directly to the facade by using PostSharp (will be discussed in the next post).


Don't forget to include the Spring.Aop.Framework namespace.

Normally the flexibility of Spring.NET is very benefitial: you can use the IoC module and inject the advice using the configuration file. In the first version, I did the same, but I realized that I don't want to change the configuration, I don't want to replace the error handling logic. The exception handling should work without configuration file, bacause inproper/missing configuration can cause exceptions. So I decided to avoid using the IoC modul of Spring.NET for logging.

Now you can't compile, because you don't have the SpringErrorHandlerAttribute class. In turn this is the heart of the logging and exception handling.


The following diagram shows the utilized AOP framework classes associated to the different facades.

Centralized Exception Handling using Spring.NET and PostSharp - advanded error logging with AfterThowing and OnException advices



So let's add a new class and use the Spring.Aop namespace!



Compile, run the test! GREEN! Grats, you can log all the exceptions from the business logic, you can wrap and rethrow them to the client applications as you wish.

We have clear code, without unwanted try-catch blocks in each method. It's nice, elegant, Object-Oriented and easy to maintain.

Furthermore you have have the method and args parameters, so you can log these important information.

You can download all the code examples from here.

Read full article: Centralized exception handling and logging using Spring.NET


0 comments:

Centralized exception handling and logging in .NET by AOP

4/10/2009

As I mentioned, we want to have quality software and quality code, one step to achieve this, we need advanced Exception handling. I have seen (and also developed:( ) a lot of applications with a lot of try and catch blocks. The workflow wasn't easy to understand, because 30% of the code was related to the error handling. It's even worse if we have the same implementation in all the catch blocks.
One straightforward step to avoid code duplication is to encapsulate the logging mechanism to a separated module, which could be configured and maintained at one place. For example, you can integrate Microsoft Enterprise Library Exception Handling Application Block.
But we still have the ugly try/catch blocks everywhere... I mean everywhere we need it: at the application/service boundary to catch unhandled exceptions (and at other places where we can recover the application state from the exception).

How handle and log exceptions and avoid writing try/catch blocks at the same time?



I was tired to write (copy-paste) error handling to all the methods in our service facade, so I did a research about this, but I haven't found any object-oriented way to solve the problem.
The key solution is related to Aspect-Oriented Programming.

You can read a short introduction of AOP at Spring.NET website.

I'm not an AOP expert, so I use AOP framework only for this purpose, and copy two quotes from the www.springframework.net

Advice: Action taken by the AOP framework at a particular joinpoint. Different types of advice include "around," "before" and "throws" advice.
Throws advice: Advice to be executed if a method throws an exception. Spring.NET provides strongly typed throws advice, so you can write code that catches the exception (and subclasses) you're interested in, without needing to cast from Exception.

Quite easy:

  • we define an action, which should be executed in case of exception (this is the advice)

  • associate the action to the target code, which should have exception handling

I tried the mechanism with different AOP frameworks: Spring.NET and PostSharp Laos. Both can be used for centralized exception handling, the basics are the same, but the 2 frameworks have one main difference: Spring.NET operates in run-time, PostSharp does the work in compile-time.

I recommend you to try both of them, I show you how to use them in C#... stay tuned!

Read full article: Centralized exception handling and logging in .NET by AOP


0 comments:

Test method inheritance with NUnit and VS Test Framework

3/28/2009

Today I finished the implementation of the centralized exception handling demo. After adding comments to the code, I wanted to begin the related article. I decided to dedicate a post to one practice, which is test method inheritance.

How to inherit and reuse unit test methods by NUnit and Visual Studio 2008 Unit Testing Framework?

The goal is simple: keep your tests clean and avoid duplicated code.
If I have inheritance in my production code, usualy I have inheritance in my test code as well.

For example, in my application, I have the Person class and I inherit the SpanishPerson and the HungarianPerson classes from this. I don't want to test the Person, because it has only abstract methods, but I want to test the two concrete classes in the same way.


To do this:

  • create a PersonTestBase class, with a _person field with Person type
    create the SpanishPersonTest and HungarianPersonTest classes

  • inherit the SpanishPersonTest and HungarianPersonTest from the PersonTestBase

  • if you are using VS Test Framework, make sure you don't have the [TestClass] attribute on the PersonTestBase, and add the [TestClass] attribute to the two concrete test classes

  • if you are using NUnit, make sure you don't have the [TestFixture] attribute on the PersonTestBase, and add the [TestClass] attribute to the two concrete test classes

  • assign the correct instance to the _person field in the SetUp/TestInitialize methods

  • add generic assertions to the base test class by decorating the methods with [Test]/[TestMethod] attributes


Sorry for the stupid example, I had no better idea :)




Using this pattern you can avoid code duplication in your tests for classes with the same baseclass, and if you want, you can write special (non-generic) test methods in each derived test classes. The code will be cleaner, easier to understand, easier to maintain.
It's a quite easy step to improve the code quality, isn't it?

Read full article: Test method inheritance with NUnit and VS Test Framework


5 comments:

Code and software quality by advanced exception handling in .NET

3/13/2009

I'm crazy about exception handling. Not because I like when an exception occurs in the live environment, but because handling them in a proper way can help us to find defects in our system. I have an own exception handling-related process, which helps me to garantee better code quality and - of course - software quality. I'm a .NET developer, so I have .NET examples in C#, but this technique can be adopted to JAVA if you want. This is the first place time I publish it, I kept it in secret till now, so I'm very excited, I hope you feel the same :)

You probably use some cool logging framework or component to persist errors somewhere. In the .NET World most people use Log4Net, Microsoft Enterprise Library Logging Application Block or Common.Logging. These are very useful tools, all of them are easy-to-use, flexible and excellent software.

I don't want to compare these tools, you probably have preferred one. I want to point out that using these logging components isn't enough in enterprise application development.


I assume you follow all exception handling principle:


  • you don't write empty catch blocks

  • you don't throw unnecessary exceptions

  • you don't reset the call stack by rethrowing the same exception after a catch

  • you free up resources in the finally block or you use the using statement
...
The rest of the basics can be found in these articles:
[MSDN] - Best Practices for Handling Exceptions
[CodeProject] - Exception Handling Best Practices in .NET
[Howard Gilbert (Yale University)] - Exception Handling in Java and C#

All the techniques are essential above, but all of us can make mistakes, so we can't be sure that our software handles exceptions correctly.

How to implement error logging functionality in .NET with quality code?

Review your code!

I usualy make a code review after each SCRUM sprint by looking for catch blocks in the code. Quite easy work, I just press CTRL-SHIFT-F in Visual Studio and look for the "catch" keyword. I analyze the code to check if it conforms to the standards.

Sometimes we concentrate to a functionality and not to the error handling. No problem, here I'm, I will do code review. I recommend you to add this task to the checklist of your each iteration, or assign this work to somebody in the team.

How can you be sure, that your code handles each exception in a correct way?

Check your code coverage report, find uncovered catch block and add test cases to cover them. I'm not competent in determining magic numbers, how much percent are enaugh for test coverage, I check only what is not covered. I'm looking for "catch" blocks here as well. If I find some, I immediately write unit tests.

I prefer writing more unit tests related to exceptions, here you can take advantage of the ExpectedException attribute of NUnit or your favourite unit testing framework.

Using this practice you can assert:
  • if you have the correct, descriptive error message, which will help you to find mistake after reading the error log

  • if you have user-friendly error message, which doesn't contain technical details


I use TDD, so after producing red/green bars and refactoring the code, I usually call my methods with bad parameters/invalid data. All TDD professional tell this, you can find it in any TDD or unit testing book, but developers sometimes concentrate only to write assertions to check the behavioral expected by the user story/functional requirement.

Recoverable and unrecoverable exceptions are not the same


If you can recover the state of your object while catching the exception in your method, handle the exception and log it if it is necessary. But if you find that you can't recover, consider deleting your try/catch block and let your caller to handle the exception. In most cases, you -should- have exception handling at your application/service boundary, so the detailed error descriptions can't get to the client or user interface. So if you are developing a code, which isn't located at the application/component boundary, catch the exception only if you can do any useful with it.

How to make sure of your logging code does not make errors in your application?


Your logging-related code must be bullet-proof.

If your logging mechanism fails, the original error and the arisen error must be written to some other location.
If you get a failure during the logging, you must avoid throwing exception to your application.

My last advice can be utilized in the deployment phase of the development life cycle.
After installing to the production server, generate an error in your application (rename a necessary file or stop a service) to make sure your live environment logs the errors.

I have some tricks for centralized exception handling/logging, so keep checking the updates of CodeRecycling ...

Read full article: Code and software quality by advanced exception handling in .NET


0 comments:

codeRecycling.Start();

3/01/2009

This will be only an introduction to the topics I want to write about in the future. Most bloggers begin the blog with this kind of post, you can see that this is the second one for me...
I had some SharePoint projects in 2007 and 2008, but I left Budapest, Hungary in the second half of 2008 and moved to Barcelona, Spain. I tried to collect some ideas for MOSS developers before I forget. Now I'm working on a product, which is not related to MOSS, so I think there will be no posts in MOSS category for a while.
But, it would be very interesting to write posts about SharePoint, because:

  • much more people work with it now than 1 year ago
  • I received 8 e-mails from recruiters and personnel consultants in the last 2 weeks, 7 were related to MOSS developer position

So look at that post as the 0. element, the real blog content begins here!


The most important thing is that 7 months ago I changed to Test-Driven Development, after this period I learnt a lot, made a lot of mistakes and learnt again from my mistakes.

During test-driven development we have to refactor our code. Sometimes I find an interesting solution and try to not forget it. To avoid loosing information, I will post my personal notes to the blog.

I had my first professional enterprise .NET project in 2005, since that time I met a lot of specialists. As I've always been very inspired and keen to learn from others, I've collected tons of beneficial tricks. I don't want to keep these tricks for myself, so these will be discussed here.

Sometimes I had problem when I had to add new functionality to an existing component. The code quality was the biggest issue always. Sometimes I refactored the code quite fast, but there were times when I was goggle-eyed while watching the code. I will share my own experience, how to improve code quality in C#.

People think different, so developers design different. I show you the way the OOP saved me a lot of time for me and the way I redesigned my own applications.

As you can see, my aim is to provide quality code and reduce development and project time. If you are familiar with Extreme Programming, you can discover, that I take advantage of XP principles.

I still have to learn and practice unit testing-related techniques, refactoring, etc. You can find much smarter professionals with more entertaining style, who can explain things much better, but I hope you will find useful information in the CodeRecycling blog as well.

Stay tuned!

Read full article: codeRecycling.Start();


0 comments: