Sunday, March 2, 2008

Custom ORDER BY in SQL

.NET provides very useful techniques for custom ordering, e.g. generic comparison delegate, lambda expressions, IComparable interface etc.

When the sort order is needed at database layer, you can use the following statement:


FROM ContestParticipants


CASE result

  WHEN 'winner' THEN 1

  WHEN 'loser' THEN 2

  WHEN 'dnf' THEN 3

  ELSE 4


kick it on

Monday, January 14, 2008

How to Test Private Fields and Methods using NUnit

When you write unit tests, you need call some methods and compare their results with expected values as well as check overall state of objects through fields and properties. It is good to separate tests from testing code. But, what about testing private fields and methods? In addition, tests may be in a standalone assembly. Have a look at the possible ways:

everything is publicBreaks API
private -> internalKeeps API, but tests must be in the same assmebly
private -> internal, InternalsVisibleToAttributeKeeps API and tests may be in separated assembly

The last way is the right one. internal modifier is clear. Be careful about protected fields, their modifier should be protected internal. All members are visible within the scope of assembly, but tests are in a separated assembly. What now? The InternalsVisibleToAttribute comes in handy.

InternalsVisibleToAttribute is supported in .NET framework 2.0 and higher. This attribute specifies the "friend assembly" - assembly, that has access to all internal members. So, the last one step is to add the following line to AssemblyInfo.cs file:

[assembly: InternalsVisibleTo("FriendAssemblyName, PublicKey=...")]

kick it on