单元测试不会“覆盖”简单的get方法。 (C#)

时间:2014-01-21 14:20:31

标签: c# unit-testing microsoft-fakes

我有一个简单的“获取”方法。例如:

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;
    }
}

我编写了一个简单的测试,执行并成功传递,但我没有获得该方法的代码覆盖率。

[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);
    }

我也试图定位类本身,它提供了覆盖但不返回任何结果(例如:“var target = new StubFoo();”)

再次,它成功执行并通过,但我没有得到任何报道。任何指针将不胜感激。感谢。

3 个答案:

答案 0 :(得分:2)

Foo.GetSomething()有0代码覆盖率,因为你从未在测试中调用它。 相反,你调用StubIFoo.GetSomething()。

var target = new StubIFoo();更改为var target = new Foo();,删除初始化StubIFoo的代码,您将获得一些保障。

Stubs可以阻止你使用(和测试)真正的类。但是你不能使用你正在测试的类的存根!

答案 1 :(得分:0)

在测试中,您不是在调用方法GetSomething,而是在属性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;

答案 2 :(得分:0)

以下是您应该做什么的一般概念

public class Foo : IFoo
{
    IDbAccess db;

    // Pass the interface, do pass parameters to create it inside constructor
    public Foo(IDbAccess db)
    {
        this.db = db; 
    }

    public Dictionary<string,string> GetSomething(string xyz)
    {
        var result = new Dictionary<string,string>

        // ... Go to DB and return some key value pairs
        result.Add(db.MethodWhatever(xyz));

        return result;
    }
}

[TestMethod()]
public void GetSomething()
{
    var dbMock = new DatabaseMock(); // This implements IDbAccess
    var target = new Foo(dbMock);

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

    // get something
    var results = target.GetSomething("xyzstring");

    // verify results
    var actual = results.whatever;

    CollectionAssert.AreEqual(expected,actual);
}