Search code examples
c#unit-testingmicrosoft-fakes

Unit test won't "cover" simple get method. (c#)


I have a simple "Get" method. Ex:

public class Foo : IFoo
{
    public Dictionary<string,string> GetSomething(string xyz)
    {
        var result = new Dictionary<string,string>
        ... Go to DB and return some key value pairs
        return result;
    }
}

I wrote a simple test that execute and passes successfully but I'm not getting code coverage on the method.

[TestMethod()]
    public void GetSomething()
    {
        var target = new StubIFoo();

        var expected = new Dictionary<string, string> 
        {
            {"blahKey","blahValue"}
        };

        var results = target.GetSomethingString = s =>
        {
            var result = new Dictionary<string, string> {{"a", "b"}};
            return result;
        };

        var actual = results("a");

        CollectionAssert.AreEqual(expected,actual);
    }

I also tried to target the class itself, which provides the coverage but doesn't return any results (ex: "var target = new StubFoo();")

Again, it successfully executes and passes but I'm not getting any coverage. Any pointers would be appreciated. Thanks.


Solution

  • In your test you are not calling the method GetSomething, but instead are setting a value to the property GetSomethingString.

    // Here is the problem. This:
    var results = target.GetSomethingString = s =>
    {
        var result = new Dictionary<string, string> {{"a", "b"}};
        return result;
    };
    // Is equal to this:
    var lambda = s =>
    {
        var result = new Dictionary<string, string> {{"a", "b"}};
        return result;
    };
    var results2 = target.GetSomethingString = lambda;