从测试方法传递空对象

我有一个类Class1,它有一个构造函数和几个方法。对于这些方法,我正在使用 MSTest 编写单元测试用例。这堂课看起来像这样。


class Class1

{

    Order order = new Order(); // there is an class Order

    public Class1(Order _order)

    {

        order = _order;

    }

    public virtual async Task<bool> GetData()

    {

        if(order != null)

        {

            //do something

        }

        else

        {

            // do something else

        }

    }

}

现在,我必须为此 GetData() 方法编写 2 个测试用例,分别测试 if 块和测试 else 块。我能够成功测试 if 块,但无法测试 else 块。我正在尝试编写的测试方法如下。


[TestMethod()]

public void GetDataTest()

{

    Order order = new Order();

    order = null;

    var mockService = new Mock<Class1>(order)

    {

        CallBase = true

    };

    var result = await mockService.Object.GetData(); // error thrown from here

    Assert.IsFalse(result);

}

我想要做的是将订单对象设置为空并将空对象传递给构造函数。但这会引发一些错误“找到歧义匹配”。显然,传递空值在这里不起作用。所以任何人都可以告诉我测试 else 块的任何其他工作。


PS:我需要测试 if 和 else 块,以便将其包含在代码覆盖率中。


宝慕林4294392
浏览 209回答 3
3回答

梵蒂冈之花

如果您的代码是真实的,那么实际上不需要模拟被测服务。这工作得很好:[TestMethod]public async Task GetDataTest(){&nbsp; &nbsp; //Arrange&nbsp; &nbsp; Order order = null;&nbsp; &nbsp; var c1 = new Class1(order);&nbsp; &nbsp; //Act&nbsp; &nbsp; var result = await c1.GetData();&nbsp; &nbsp; //Assert&nbsp; &nbsp; Assert.IsFalse(result);}

波斯汪

您必须从“GetData()”返回public virtual async Task<bool> GetData()&nbsp; &nbsp;&nbsp;{&nbsp; &nbsp; if(order != null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //do something&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // do something else&nbsp; &nbsp; }//return task here with await keyword;}

PIPIONE

好吧,单元测试用例和您共享的代码没有任何问题除了您没有返回任务,并且错误“找到了歧义匹配”看起来来自编写在 else 块中的代码内部。尝试将您的GetData()方法更改为:public virtual async Task<bool> GetData()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TaskCompletionSource<bool> ts = new TaskCompletionSource<bool>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (order != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //do something&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ts.SetResult(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // do something else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ts.SetResult(false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return await ts.Task;&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP