Mocking method with Action parameter

后端 未结 2 606
陌清茗
陌清茗 2021-01-11 21:09

[unit testing newbie] [c#]

Consider the following scenario:

I\'m using Silverlight and calling a WCF service. Silverlight can only call WCF services

2条回答
  •  春和景丽
    2021-01-11 21:26

    Here is some pseudo code, I haven't run it. But I think that's what you want.

    SetupCallback is what you are interested in.

    For all the calls to _meetingRoomServiceFake.GetRooms, simply set the _getRoomsCallback to the parameter passed in.

    You now have a reference to the callback that you are passing in your viewmodel, and you can call it with whatever list of MeetingRooms you want to test it. So you can test your asynchronous code almost the same way as synchronous code. it's just a bit more ceremony to setup the fake.

    Action> _getRoomsCallback = null;
    IMeetingRoomService _meetingRoomServiceFake;
    
    
    private void SetupCallback()
    {
         Mock.Get(_meetingRoomServiceFake)
             .Setup(f => f.GetRooms(It.IsAny>>()))
             .Callback((Action> cb) => _getRoomsCallback= cb);
    }
    
    [Setup]
    public void Setup()
    {
         _meetingRoomServiceFake = Mock.Of();
         SetupCallback();
    }
    
    [Test]
    public void Test()
    {
    
          var viewModel = new SomeViewModel(_meetingRoomServiceFake)
    
          //in there the mock gets called and sets the _getRoomsCallback field.
          viewModel.GetRooms();
          var theRooms = new List
                       {
                           new MeetingRoom(1, "some room"),
                           new MeetingRoom(2, "some other room"),
                       };
    
         //this will call whatever was passed as callback in your viewModel.
         _getRoomsCallback(theRooms);
    }
    

提交回复
热议问题