tags:

views:

86

answers:

7

The following is a failing unittest explaining a bug I found today:

    [TestMethod]
    public void WFT()
    {
        string configDebug = "false";
        bool configDebugEnabled = bool.TryParse(configDebug, out configDebugEnabled);

        Assert.AreEqual(false, configDebugEnabled);
    }

This is how to make the test go from red to green:

    [TestMethod]
    public void WFT()
    {
        string configDebug = "false";
        bool configDebugEnabled;
        bool.TryParse(configDebug, out configDebugEnabled);

        Assert.AreEqual(true, configDebugEnabled);
    }

I haven't been able to find the paragraph explaining this in the C# specification but there's most likely a decent explanation to this behaviour. Can anybody explain to me why the first test is failing?

+5  A: 

Because the TryParse method always returns true if the parsing succeeds and false if not. In the first case the parsing succeeds so configDebugEnabled = true which is not what you assert.

Btw the second test will also fail unless you write string configDebug = "true".

Darin Dimitrov
+2  A: 

The reason it's failing is that you are using the same variable to store the success or failure of the TryParse itself. As the parsing succeeds (the string does translate to a boolean value) you are overwriting the returned value of false with true.

ChrisF
A: 

Why would you expect the out parameter to return true?

leppie
+1  A: 

Because the return parameter from bool.TryParse is "true" if it was able to do the conversion or not -- the return parameter is not the result of the conversion.

You're overwriting the result (in the out parameter) with the return from bool.TryParse() itself.

Dave Markle
A: 

bool.TryParse returns a bool to specify whether the parse was successful. You are assigning that result to the same bool variable that you are putting in the out parameter.

You need a separate variable to test for the success of the function.

Dave Arkell
A: 

You assign the variable configDebugEnabled from both the return value and from the out parameter. If the variable is false at the end you don't know if parsing failed or the parsed value was false.

do it this way:

bool IsOk;
bool configDebugEnabled = bool.TryParse(configDebug, out IsOk);
codymanix
+1  A: 

In this line

bool configDebugEnabled = bool.TryParse(configDebug, out configDebugEnabled);

the variable configDebugEnabled is first set to false (as a result of the parse), but immediately after is set to true (because TryParse returns true if the parse was successful). Why not just use bool.Parse?

Grzenio