【问题标题】:How to test functionality using unit test if flow is event based in C#?如果流是基于 C# 的事件,如何使用单元测试来测试功能?
【发布时间】:2019-05-17 06:55:22
【问题描述】:

我正在为基于事件的流程编写单元测试。让我用代码告诉你完整的流程。我有一个应用程序 App1,它向 App2 发送一些命令(一种方式)。然后 App2 在一段时间后发送事件作为响应。不清楚? 让我们简化一下。我有一个 App1,它允许用户选择一些商品,完成选择后,用户保留了所选商品,以便其他用户无法选择这些商品。 App1为预约货物,向App2发送命令,逐一预约货物。如果有 3 件商品,则 App1 将 good1 发送给 App2 进行预约,当 App2 收到事件时,App1 发送下一个商品 2 进行预约,并再次继续该过程,直到所有商品都预约完毕。我已经实现了这个功能,现在是时候为它编写单元测试了,但不知道如何处理它。文字太多,让我们看一些代码。

 public void ReserveGoods(List<Goods> items)
        {
            //Goods recived from GUI;
            if (items.Count > 0)
            {
                var item = items.First();
                //_agent is nothing but a class to communicate with App2
                _agent.ReserveGood(item.SectNo);
                //After this method, On GUI the status of process is pending unit the else part not run.
            }
            else
            {
                NotifyToGui(Response.GoodsReserved);
            }


        }

        //Event recived from App2
        private void ReadyToProcessNextGood(object sender, ReadyToStartNewGoodItemEventArgs e)
        {
            var processId = e.ProcessId;
            //Remove reserved good.
            _ItemRepository.Delete(e.SectNo);
            var items = _ItemRepository.GetGoodsByProcessId(processId);

            //Going to reserve remaining items
            ReserveGoods(items);
    }

我想为此流程编写单元测试。我可以像调用事件 ReadyToProcessNextGood 一样模拟 _agent.ReserveGood(item.SectNo) 方法,但是在调用之后,如何进入 ReadyToProcessNextGood 事件。

【问题讨论】:

    标签: c# unit-testing rhino-mocks


    【解决方案1】:

    我会把它分成两部分。

    1. 测试业务功能,酌情使用单元测试/集成测试
    2. 使用集成测试测试整个事情。

    我的做法是这样的:

    首先进一步分解代码以从中删除事件部分。类似:

     private void ReadyToProcessNextGood(object sender, ReadyToStartNewGoodItemEventArgs e)
        {
                //maybe some checks here to make sure you have the right data
                BusinessMethodHere(e.processId, e.SectNo);
        }
    
    public void BusinessMethodHere( string processId, string sectNo )
    {
                //Remove reserved good.
                _ItemRepository.Delete(sectNo);
                var items = _ItemRepository.GetGoodsByProcessId(processId);
    
                //Going to reserve remaining items
                ReserveGoods(items);
    }
    

    现在您可以在事件调用之外单独测试业务功能。 继续解耦您的业务并正确测试。

    最后创建一个实际上依赖于事件的集成测试,并确保它正确地流经系统。那时您不需要测试业务功能,因为您已经通过单元测试/其他集成测试完成了这项工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-20
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多