MorningLightMountain

a little something from an immotile

Posts Tagged ‘C#’

Timing integration tests

Posted by Dan G on November 30, 2011

Once more Fluent Assertions has come in handy for providing a simple way of asserting the execution time of an Action (in this case a big bit of data formatting), buried away almost as foot note on their docs page is:

New in version 1.4 is a method to assert that the execution time of particular method or action does not exceed a predefined value. To verify the execution time of a method, use the following syntax:

var subject = new SomePotentiallyVerySlowClass();
subject.ExecutionTimeOf(s => s.ExpensiveMethod()).ShouldNotExceed(500.Milliseconds());


Alternatively, to verify the execution time of an arbitrary action, use this syntax:

Action someAction = () => Thread.Sleep(510);
someAction.ExecutionTime().ShouldNotExceed(100.Milliseconds());


Since it doesn’t make sense to do something like that in Silverlight, it is only available in the .NET 3.5 and .NET 4.0 versions of Fluent Assertions.

Make sure to set a sensible execution limit – bear in mind who’s running the tests (might be slow hardware – false negatives ahoy). It’s considered polite to put a Category attribute with a “Slow” value so people can exclude long running integration tests.

Posted in Tools | Tagged: , , , | Leave a Comment »

Read the Stream.Read fineprint

Posted by Dan G on November 12, 2011

Before you repeat this anti-pattern:

using (var stream = new FileStream("myFile.txt",FileMode.Open))
{
    var bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);
}


Make sure you’ve read the MSDN docs for Stream.Read :

Stream.Read Method

When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)

public abstract int Read(
	byte[] buffer,
	int offset,
	int count
)


Parameters
buffer
Type: System.Byte()
An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count – 1) replaced by the bytes read from the current source.

offset
Type: System.Int32
The zero-based byte offset in buffer at which to begin storing the data read from the current stream.

count
Type: System.Int32
The maximum number of bytes to be read from the current stream.

Return Value
Type: System.Int32
The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

Notice the wording for count? Maximum number of bytes to be read, and the return value is how many were actually read. There’s no guarantee that the stream will able in any fit state to serve your request for all the bytes in one go. The following, whilst longer, does ensure you read all the bytes from the stream, every time. Guess where the examples from? That’s right – the MSDN page:

Stream s = new MemoryStream();
for (int i = 0; i < 100; i++)
{
    s.WriteByte((byte)i);
}
s.Position = 0;

// Now read s into a byte buffer.
byte[] bytes = new byte[s.Length];
int numBytesToRead = (int) s.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
    // Read may return anything from 0 to 10.
    int n = s.Read(bytes, numBytesRead, 10);
    // The end of the file is reached.
    if (n == 0)
    {
        break;
    }
    numBytesRead += n;
    numBytesToRead -= n;
}
s.Close();
// numBytesToRead should be 0 now, and numBytesRead should equal 100.
Console.WriteLine("number of bytes read: {0:d}", numBytesRead);

Posted in Good practie | Tagged: , | Leave a Comment »

Fluent Assertions and exception testing

Posted by Dan G on November 12, 2011

Way back when (20th October 08 to be precise) whilst at iMeta I blogged about extending the exception testing capabilities in NUnit, using a little homebrew class that I then carried with me everywhere.

The basic problem the class solved was of imprecision in asserting the source of exceptions using the [ExpectedException] attribute:

[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void DoStuff_Throws_ArgumentNullException_For_Null_Argument()
{
    // arrange
    var myObj = new VolatileObject(null);

    // act
    myObj.DoesStuff(null);
}

public class VolatileObject
{
    public VolatileObject(object ctor)
    {
        if (ctor == null) throw new ArgumentNullException("ctor");
    }

    public void DoesStuff(object parameterName)
    {
        if (parameterName == null) throw new ArgumentNullException("parameterName");
    }
}


If the VolatileObject constructor call throws ArgumentNullException (as it will, we’re passing null), the test will pass. That’s not what we’re testing, we’re testing that a call DoStuff with null throws an ArgumentNullException (hence the test name of DoStuff_Throws_ArgumentNullException_For_Null_Argument(). The attribute approach is too coarse grained. As I said, I used to use my own class, but since picking up Fluent Assertions I’m naturally using their implementation, either way the approach is the same, focus down the scope for thrown exceptions:

[Test]
public void DoStuff_Throws_ArgumentNullException_For_Null_Argument()
{
    var myObj = new VolatileObject(null);

    Action act = () => myObj.DoesStuff(null);
    act.ShouldThrow().WithMessage("parameterName", ComparisonMode.Substring);
}


Notice that we’re focusing the assertion around just the call that should result in an exception (the Action act). Additionally we can make assertions about the the message of the exception, is this case making sure the correct parameter name shows up using a Substring comparison.

Of course we’re still passing null to the constructor, so the test now fails! Just as it should have done before. Chuck anything into the constructor and the test now passes when DoesStuff throws an exception.

I’ve been using Fluent Assertions a lot to simplify the expression of my assertions:

[Test]
public void Stuff_Should()
{
    string.Empty.Should().NotBeNull();
    string.Empty.Should().HaveLength(0);
    ((object)null).Should().BeNull();
    "1234".Should().Be("1234");
    100.Should().NotBe(99);
    DateTime.Now.Should().BeAfter(new DateTime(1900, 1, 1));
    Colors.Red.Should().NotBe(Colors.Green);
    (-1).Should().BeLessThan(0);
    1.Should().BeGreaterThan(0);
}


How straightforward is that? Even better – should a condition fail, you’ve given Fluent Assertions more than enough information to provide a neat explanation of the failure and the conditions.

Posted in Good practie | Tagged: , , , | 1 Comment »

Never lock another mans Type

Posted by Dan G on November 11, 2011

Something I’ve come across a lot of in the past is use of the lock statements on publicly exposed things (types, instances) :

lock(this) {
lock(typeof(MyTypeWithALock)) {


Both examples are bad for the same reason – the thing you’re locking on is public. So anyone within your app domain can lock on the same thing, deadlock city looms. If it’s your lock, keep it private, it doesn’t take long to put in a field, either instance or static, and it only has to be a simple object. Get into the habit and avoid a future “WTF is going on?” moment or two.

Bonus point : this answer on Stack Overflow explains an extra definition of public – between appdomains in the same process.

Posted in Good practie | Tagged: , | Leave a Comment »

Resharper Live Templates & More on GitHub

Posted by Dan G on November 9, 2011

One last thing tonight, I’ve started storing my own Resharper Live Templates in a public repo on my GitHub account. They’re broken up by category into individual files so they’re a bit easier to manage, though all, I’m afraid, for C#.

I’ve also put up a small demo app that I built whilst working with @annie_watkins showing how Structure Map can be used by WCF to inject dependencies into services, as well as why dependency inversion is a good thing with mocked unit tests. I’m might do a quick article on it in the near future.

Finally I’ve made progress with the branch of RHAL9000 (imaginatively titled  Rebuild_1) where I’m seperating the source of the data and their synchronization away from the view models and the ultimately the UI. Hopefully more on this project soon.

Posted in Tools | Tagged: , , , , , , | Leave a Comment »

ISP done – one more SOLID poster to do

Posted by Dan G on November 7, 2011

Just finished off ISP, quite happy with it given how long it’s taken. All the others (except DIP) in Motivational Posters.

Posted in Good practie | Tagged: , , , | Leave a Comment »

Simple DRY example

Posted by Dan G on November 7, 2011

I’ve been working on a data repository that’s take bits of an object model and is calling existing SPROCs. Part of the mapping process is this block of code (a common pattern you’ll see many times, and possibly in many different forms):

// Build address string
string address = "";

if (cai.Address1 != null) { address += cai.Address1 + ", " + Environment.NewLine; }
if (cai.Address2 != null) { address += cai.Address2 + ", " + Environment.NewLine; }
if (cai.County != null) { address += cai.County + ", " + Environment.NewLine; }
if (cai.Town != null) { address += cai.Town + ", " + Environment.NewLine; }

address = address.Trim();
if (address.Length > 0 && address.LastIndexOf(',') == address.Length - 1)
{
	address = address.Substring(0, address.Length - 1);
}


A variation of this would be :

var builder = new StringBuilder();
foreach(var thing in listOfThings)
{
	if (thing != null)
	{
		builder.Append(thing.ToString());
		builder.Append(", ");
		builder.Append(Environment.NewLine);
	}
}
var stringOfThings = builder.ToString().Trim();
if (stringOfThings.Length > 0 && stringOfThings.LastIndexOf(',') == stringOfThings.Length - 1)
{
	stringOfThings = stringOfThings.Substring(0, stringOfThings.Length - 1);
}


This pattern is so common it’s not really funny. Basically we need to append a bunch o’ strings together with a seperator (if they’re not null) and make sure there’s not a dangling comma. So far, so relatively ordinary. But look at that code again. The rule, ‘value must not be null’, is repeated 4 times, as is the rule, ‘seperated by ", " + Environment.NewLine’. Also if you wanted to add another line into the address you’ve got to repeat both rules again. This is a violation of the DRY principle (Don’t Repeat Yourself). Now you can extract the ", " + Environment.NewLine out into a variable, but you’ve still repeated the null check. Worse you’ve had to include a particularly error prone bit of code at the end to clean off the hanging comma (the common error you can get here is an off by one). Consider the following replacement:

var validParts = new[] { address.Line1, address.Line2, address.Town, address.County }.Where(p => p != null);

return string.Join(", " + Environment.NewLine, validParts);


And for our variation:

var validParts = listOfThings.Where(t => t != null);

return string.Join(", " + Environment.NewLine, validParts);


Now doesn’t that make you feel better? Stick all our elements into an array, filter out null ones, and then join them with our seperator. Each of our pair of rules is implemented only once (the condition in Where(p => p != null), should really be !string.IsNullOrEmpty(p) but I’m making sure to stick to the existing data contract.) The string.Join method is only putting the seperator in between each element, not after the last one so no need for the error prone clean up. We could go one step further and write it as

return string.Join(", " + Environment.NewLine, new[] { address.Line1, address.Line2, address.Town, address.County }.Where(p => p != null));

But I think the intent gets slightly lost, which is why I kept the former. However both conform to DRY, each rule is stated once and ONLY once. Change is easy to accomodate and we’ve deliberately avoided writing error-prone code.

Posted in Good practie | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 165 other followers