VS15 can add conditions to exceptions!

1 comment

Wednesday, April 06, 2016

Last week at (or rather during) //Build conference a new Visual Studio was unveiled. You can download the preview right now – I’ll wait…

Getting a new Visual Studio feels like Christmas morning (if I was celebrating Christmas). There’s always cool features to explore and new things to play with, an improved shade of purple of the infinity icon – good stuff!

I was browsing the VS15 release notes (not to be confused with the previous VS2015) when I saw a cool feature I always wanted. In fact I was asked for that specific feature during one of the many OzCode’s demos. That feature is the ability to add an condition to when (or rather where) to break on an exception.

.NET exceptions are great, they help me understand when my code misbehave and I get to use quite a lot. The problem is catching those tricky bastards. Usually when I try to squash a bug that cause an exception I want to break when that exception is thrown. To do so I would usually open the Exception settings dialog and tell Visual Studio to break when a specific exception is thrown.

So, if I have a console application that uses two external libraries both with bugs, but only one I care about:

static void Main(string[] args)
{
    var mineAllMine = new MyClassLibrary.MyClass();
    var buggyCode = new OtherClassLibrary.ExternalClass();

    try
    {
        buggyCode.SomeMethod();
    }
    catch (Exception)
    {
        Console.WriteLine("Buggy code exception");
    }

    try
    {
        mineAllMine.AmazingMethod();
    }
    catch (Exception)
    {
        Console.WriteLine("Performed according to spec!");
    }
}

And since I cannot fix the external class (and its buggy code) we want to only break on exceptions thrown from our own superior (and amazing) method.

Doing so with VS15 is simple simple open Visual Studio’s Exception settings and choose, or better yet search for the exception you want mark it and then press the small pencil icon to add an condition.

image

Right now we can only choose on which module to break (or which module not to break).

And it works like a charm.

IMHO Debugging just got better and hopefully will continue to improve.

 

Until then – happy coding…

A few days ago Microsoft has finally announced that some of the old(er) windows phones would soon get the new shiny OS. That left a few windows phone owners a little disappointed. I remember that only a few months ago it was clear that all (or at least most) windows phone devices would be updated to Windows 10 and now it seems that they would in fact keep running windows 8.1.

As the proud owner of one Lumia 925 – I feel a little cheated, but not surprised. I have used the insider builds of the latest and greatest for a few weeks, and while I enjoyed using the new OS it was not “production ready” just yet.Nokia-Lumia-925-smartphone-Black-update-jpg

This is not the first time I’ve tried the insider builds – about a year ago when I just got my phone I immediately installed the newest version I could get my hands on – and then removed it after less than 4 hours (and 3 failed attempts). I was buggy, crashed all the time and basic capabilities (a.k.a calling other people) would not work.

This time around the new version worked better, I got most of the functionality (call app still crashed though) and I liked what I saw and was ready for the next version that would crash the bugs I kept on reporting – which today I know would likely not happen.

Part of being in the insider program was that my phone kept asking me if I’m happy with the current experience and whether I would recommend this particular build to a friend. I would answer that I am happy but a few glitches still preventing me from telling someone else to try it out. My aim was to provide feedback so that the things that bothered me the most would be addressed. Another tings I learnt since is that Microsoft was also using this feedback to decide which devices would get the new OS and which would be left out.

Don’t get me wrong – I think that from a business perspective this is a good path to go. The next version of Windows mobile should be released and decreasing the scope and/or supported devices is one way to do so.

There is another aspect to this decision: One thing I cared about for all of the phones I owned in the past (I tend to break them – a lot) is that no matter the OS I wanted it to get updated.

I want the latest and greatest – even with an older phone. In the past I bought Nexus 4 phone because at the time it that was the only Android phone that consistently got updated and for the same reason I got my latest phone as well. As a user I hate the practice of some vendors – which don’t bother to update the phones firmware just because it’s not economically viable – or is it?

I had some work in the Windows phone 8, then UWP (Universal Windows platform) 8.1 and 10 space. And decision like this that make me a bit worried.

I worked for a company that made an investment and created a windows 8 app. Before we managed to complete it – there came //build announcing that the way to go from now on is to write Universal apps (8.1). We made an effort and managed to convert most of the code to the new platform, and we were waiting for some crucial functionality when the next //Build came along and kindly explained that the old Universal Apps (a.k.a 8.1) were over and there’s a new platform now. At that point the managers got a little worried.

It seemed that every year there’s a change and the new shine we were working on was now obsolete. I guess we were lucky we haven’t started a year before working on Windows 7 apps (remember those)…

I love my phone – it works amazingly, has a good battery life and I love the user experience (tiles!) but when I’m asked about it I feel the need to apologize – because there are not a lot of applications for it. As a developer I completely understand why – companies don’t want to invest in new platform and by the time it seems stable enough – it gets replaced. The low market share of Windows phones doesn’t help either, but users won’t buy a phones that don’t have their favorite app – do you see the magic cycle yet?

The next //Build conference starts this Wednesday – and as a software developer and (a proud) Windows phone owner I’m both excited and worried. I want to learn about the new, cool stuff but I fear that just like the last time I would also learn which technologies are going to kick the bucket.

Nokia-Lumia-925-front-png Until then – Happy coding…

Comparing Two objects using Assert.AreEqual()

4 comments

Monday, March 21, 2016

Anyone who ever googled (binged?) about unit testing have heard about the “one assert per test rule”. The idea is that every unit test should have only one reason to fail. It’s a good rule that help me write good, robust unit test – but like all such rules-of-the-thumb it’s not always right (just most of the time).
If you’ve been using unit tests for some time you might have come to a conclusion that using multiple asserts is not always a bad idea – in fact for some tests it’s the only way to go…
Consider the following class:
public class SomeClass
{
    public int MyInt { get; set; }
    public string MyString { get; set; }
}
And now imagine a test in which that SomeClass is the result of your unit tests – what assert would you write?
[TestMethod]
public void CompareTwoAsserts()
{
    var actual = new SomeClass { MyInt = 1, MyString = "str-1" };

    Assert.AreEqual(1, actual.MyInt);
    Assert.AreEqual("str-1", actual.MyString);
}
Using two asserts would work, at least for a time. The problem is that failing the first assert would cause an exception to be thrown leaving us with no idea if the second would have passed or failed.
We can solve this issue by splitting the test into two tests – one test per assert. Which seems like an overkill in this case - we’re not asserting for two different, unrelated “things”, we’re in fact testing one SomeClass that happen to have two properties.
Ideally I would have liked to write the following test:
[TestMethod]
public void CompareTwoObjects()
{
    var actual = new SomeClass {MyInt = 1,MyString = "str-1"};
    var expected = new SomeClass {MyInt = 1,MyString = "str-1"};

    Assert.AreEqual(expected, actual);
}
Unfortunately it would fail. The reason is that deep down inside our assert have no idea what is an “equal” object and so it runs Object.Equals and throws an exception in case of failure. Since the default behavior of Equals is to compare references (in case of classes) the result is a fail.
Due to this behavior there are many (myself included) who suggest overriding Equals to make sure that the actual values are compared. which could be a problem if our production code cannot be changed just to accommodate our tests.  There are ways around this limitation – such as using a Helper class (ahem) that would do the heavy lifting by inheriting (or not) the original class and adding custom Equals code.
I propose another option – one that could be useful , especially when there’s a need to compare different properties in different tests.

Using Fake objects to compare real objects

In order to change the way two objects are compared in an assert we only need change the behavior of one of them – the expect value (might change depending on unit testing framework). And who is better in changing behavior of objects in tests than your friendly-neighborhood mocking framework.
And so using FakeItEasy I was able to created the following code:
[TestMethod]
public void CompareOnePropertyInTwoObjects()
{
    var actual = new SomeClass { MyInt = 1, MyString = "str-1" };
    var expected = new SomeClass { MyInt = 1, MyString = "str-1" };

    var fakeExpected = A.Fake<someclass>(o => o.Wrapping(expected));

    A.CallTo(() => fakeExpected.Equals(A<object>._)).ReturnsLazily(
        call =>
        {
            var other = call.GetArgument<someclass>(0);

            return expected.MyInt == other.MyInt;
        });

    Assert.AreEqual(fakeExpected, actual);
}
What we got here is a new fake object a.k.a fakeExpected which would call custom code when its Equals method is called.
The new Equals would return true if MyInt is the same in the two objects. I’ve also create the new fake using Wrapping  so that the original methods on the class would still be called – I really care about ToString which I would override to produce meaningful assertion message.
Now all I needed to so is to compare the fakeExpected with the actual result from the test.
In a similar way I’ve created a new extension method that would compare the properties on two classes:
public static T ByProperties<T>(this T expected)
{
    var fakeExpected = A.Fake<T>(o => o.Wrapping(expected));

    var properties = expected.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

    A.CallTo(() => fakeExpected.Equals(A<object>._)).ReturnsLazily(
        call =>
        {
            var actual = call.GetArgument<object>(0);

            if (ReferenceEquals(null, actual))
                return false;
            if (ReferenceEquals(expected, actual))
                return true;
            if (actual.GetType() != expected.GetType())
                return false;

            return AreEqualByProperties(expected, actual, properties);
        });

    return fakeExpected;
}

private static bool AreEqualByProperties(object expected, object actual, PropertyInfo[] properties)
{
    foreach (var propertyInfo in properties)
    {
        var expectedValue = propertyInfo.GetValue(expected);
        var actualValue = propertyInfo.GetValue(actual);

        if (expectedValue == null || actualValue == null)
        {
            if (expectedValue != null || actualValue != null)
            {
                return false;
            }
        }
        else if (typeof (System.Collections.IList).IsAssignableFrom(propertyInfo.PropertyType))
        {
            if (!AssertListsEquals((IList) expectedValue, (IList) actualValue))
            {
                return false;
            }   
        }
        else if (!expectedValue.Equals(actualValue))
        {
            return false;
        }
    }

    return true;
}

private static bool AssertListsEquals(IList expectedValue, IList actualValue)
{
    if (expectedValue.Count != actualValue.Count)
    {
        return false;
    }

    for (int I = 0; I < expectedValue.Count; I++)
    {
        if (!Equals(expectedValue[I], actualValue[I]))
        {
            return false;
        }
    }

    return true;
}
And now I can use the following to compare my expected value with the value returned by the test:
[TestMethod]
public void CompareTwoObjectsByProperties()
{
    var actual = new SomeClass { MyInt = 1, MyString = "str-1" };
    var expected = new SomeClass { MyInt = 1, MyString = "str-1" };

    Assert.AreEqual(expected.ByProperties(), actual);
}
Simple(ish) is it? I prefer this method since I no longer need to make changes to my production code (e.g. SomeClass) but I can still use plain vanilla unit testing framework.

What do you think?
I’ve been working with OzCode for some time now, and every now and then I find a cool capability I didn’t know it had.
Today I wanted to investigate (read: debug) the way several objects were xml-serialized for a demo I’m preparing and for that I created the following method:
static class Xml
{
    public static string SerializeObject<T>(this T toSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

        using (StringWriter textWriter = new StringWriter())
        {
            xmlSerializer.Serialize(textWriter, toSerialize);
            return textWriter.ToString();
        }
    }
}
Now I could use the immediate window to serialize a few classes by calling it:

CustomXmlSerialize
As you might have guessed I needed to do quite a lot of scrolling and copy-pasting in order to understand this long line of xml.
Since I also needed the value for debugging I decided to try and use Custom Expressions – and it worked!
By using OzCode’s “magic wand” to create a new Custom Expression that called the new method, I got a “new” property in my object that has the full XML serialization result.
OzCodeCustomExpressionXmlSerialize
Keep in mind that it won’t work when debugging code that cannot access the method used and I recommend using the fully qualified method name (with namespace). And remember – there’s serialization code running underneath the new “property” – so consider deleting the expression once you finish using it (it can always be added back).

With this new property I was able to finish debugging several objects without stopping mid-debug to add code that had no business being there.

Happy coding (&debugging) …

Did you know that Visual Studio shows deadlocked tasks?

No comments

Wednesday, December 30, 2015

I didn’t…
And it’s not a new feature – since it existed since freaking Visual Studio 2010!
Yesterday during an unrelated meeting Alon Fliess showed a bunch of us developers how Visual Studio detects deadlocks in tasks (automatically) and shows the current task status in both Parallel Tasks and Tasks debug windows (duh).
I got home late but I wanted to experiment and see what would happen and so I wrote a simple program to see how well Visual Studio understands the bugs I can trough at it:
static void Main(string[] args) 
{ 
    int taskCount = 6; 
    var tasks = new Task[taskCount]; 
    var autoResetEvent = new AutoResetEvent(false); 
    for (int i = 0; i < taskCount; i++) 
    { 
        tasks[i] = Task.Factory.StartNew(state => 
        { 
            var index = (int)state; 
            if (index < 3) 
            { 
                tasks[(index + 1) % 3].Wait(); 
            } 
            else if (index == 3) 
            { 
                Task.Factory.StartNew(() => 
                { 
                    while (true) { } 
                }).Wait(); 
            } 
            else 
            { 
                autoResetEvent.WaitOne(); 
            } 
        }, i); 
    } 

    Task.WaitAll(tasks); 

    autoResetEvent.Set(); 
}
What a mess – I have three tasks waiting on each other (deadlocked), two more tasks waiting indefinitely on a AutoResetEvent and one task that starts yet another task that runs an infinite loop (just for fun).
After a few seconds I paused/breaked execution and got the following (Debug –> windows –> Tasks):
image
So out of the 6 tasks I spawned the first three deadlocks are detected by VS, Three tasks that show as blocked (waiting for AutoResetEvent and waiting for another task to complete). The only task that shows as running is the one that happily burning CPU on a while loop that would never end (also known as the Halting problem).
That’s good enough for me.
I guess it’s another case of a useful feature that I always wanted but didn’t know already existed.

Happy coding…

VS2015 Update 1 brings (back) parallel test execution

2 comments

Friday, December 04, 2015

Yesterday I’ve installed the new VS2015 update and tried to make my machine talk to my win10 (IoT core) Raspberry PI. It didn’t help but that’s a story for another blog post – spoiler: it was a problem with my laptops Ethernet port.

After the dust settled I’ve started reading about the new goodness that was just added to my trusty Visual Studio and found out that Microsoft has decided to give us the parallel test execution.

It all started back in the long forgotten Visual Studio 2010. Back then we had a great feature called parallel test execution. It did exactly that – reduce run speed by utilizing several cores to run tests – it was well hidden but for those of use who know where to enable it – it worked like a charm - as long as other tools, especially your Mocking framework of choice supported multi threading.

Then came VS2012 and the ability to run unit tests side by side disappeared… you could use it but for the price of using the old soon to be legacy test runner.

Since I liked the fact that my test run took less time I was happy to see that the feature I liked came back.

Enabling parallel tests is simple – first create a new test.runsetings – don’t look for a template (because there is none), just add a new xml file and rename it.

For parallel tests you just need the file to contain the following lines:


<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<RunConfiguration>
<MaxCpuCount>0</MaxCpuCount>
</RunConfiguration>
</RunSettings>

For the value of MaxCpuCount  use the number of threads you want to use (usually 1 for sequential run), or instead ‘0’ or a number greater of the number of your machine logical core (please use ‘0’).

Look under Test menu for “Select Test Settings File” and choose the newly minted (test settings) file.

image

For more information of what the test settings file can do for you – read this MSDN page.

Now when running the tests you’ll see improvement it the time it takes for them to finish.

mstest_parallelUntitled

I did notice that it took longer for the tests to start running and there’s a barely noticeable delay at the end of the run but other than that – parallel tests!

As you can see the runner runs assemblies in parallel so if you have a lot of tests in one assembly – you might not benefit from this feature, please consider splitting your tests (and probably production code as well).

I still need to check if (and which) mocking frameworks would work with this new(ish) test execution.

 

Happy coding…

When Mockito’s InjectMocks does not inject mocks

3 comments

Thursday, November 26, 2015

Looking back at the time wasted yesterday while trying to make a trivial functionality work makes me wonder if it was a good idea to begin with…

It all started  (and ended) yesterday while I was mentoring a team on the fine art of Java unit testing.

We’ve decided to use Mockito’s InjectMocks due to the fact that most of the project's classes used Spring to fill private fields (don’t get me started).

For those of you who never used InjectMocks before – in the Mockito word we can auto-magically initialize and inject mock objects into the class under test. And it’s all done using annotations.

And so if I have the following class:


public class MyClass {

@Resource
private INetworkService networkService;

@Resource
private IFileService fileService;

public boolean SomeMethod(){
// some logic here

// More logic here
networkService.Send();

return true;
}
}

I can write a test fixture that looks like this:


@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private INetworkService networkService;

@Mock
private IFileService fileService;

@InjectMocks
MyClass myClass;

@Test
public void testSomeMethod() {
boolean result = myClass.SomeMethod();

assertTrue(result);
}
}

And so the two dependencies (marked with @Mock) would be faked and inserted into MyClass by constructor, property or field injection.

The problem was that we couldn’t get it to work. The mocks were initialized and the class was created - without the dependencies. It took us some time but finally we’ve found the reason: the real class looked something like this - can you spot the difference?


public class MyClass {

@Resource
private INetworkService networkService;

@Resource
private IFileService fileService;

private Integer version;

public MyClass(Integer version) {
this.version = version;
}

public boolean SomeMethod(){
// some logic here

// More logic here
networkService.Send();

return true;
}
}

Did you see it?

In our real class we had a non-empty constructor which InjectMocks tried to use, but passed null since Integer canno be mocked by Mockito (it’s a final class). Once Mockito found a constructor to try and to use it didn’t even try to inject the two fields (lazy bastard). And so the dependencies inside the MyClass remained null causing a null reference exception to be thrown once used.

It’s not that Mockito guys didn’t do a good job, this behavior is documented – which makes it yet another case of RTFM.

The problem is that the tests who successfully run using this mechanism could one day fail just because someone decided to add another constructor…

 

Happy coding

Related Posts Plugin for WordPress, Blogger...
Top