Skip to main content

Posts

Showing posts from April, 2010

When an Object Isn’t an Object

I really wish there were more guidance on how to handle static reflection situations. Some kind of helper library would be nice. I’m actually surprised one doesn’t exist given its usefulness and the quirks involved. Consider this scenario – you’re reflecting over the details of a method call and the parameters passed. You actually care about the values that have been passed. How do you discover them? It goes something like this, I think: var argument = GetExpression(); if (argument.Type.IsValueType) { argument = Expression.Convert(argument, typeof(object)); } var getValueExpression = Expression.Lambda<Func<object>>(argument); var getValue = getValueExpression.Compile(); var value = getValue(); I found that here . If you don’t explicitly convert the value type to an object, you’ll get an exception that will confuse you (something to the effect of “Expression of type 'System.Decimal' cannot be used for return type 'System.Object'”). It’s confusing bec

Teaser

These tests all pass: [Test] [ExpectedException(typeof(AssertionException))] public void ThrowsAssertionExceptionForWrongArgument() { Expect.Call(() => Console.WriteLine("A specific string.")); StaticClass.CodeUnderTestThatCallsConsoleWriteLine(); Verify.AllExpectations(); } [Test] public void VerifiesCallWithoutActuallyPerformingTheCall() { Expect.Call(() => Console.WriteLine("You shouldn't see me.")); StaticClass.CodeUnderTestThatCallsConsoleWriteLine(); Verify.AllExpectations(); } [Test] public void PerformsAlternativeAction() { Expect.Call(() => Console.WriteLine("YOU SHOULDN'T SEE THIS")).IgnoreArguments() .Do(() => Console.WriteLine("You should see this instead.")); StaticClass.CodeUnderTestThatCallsConsoleWriteLine(); Verify.AllExpectations(); } [Test] public void IgnoresArguments() { Expect.Call(() => Console.WriteLine("")).Ign