[單元測試新手] [C#]與行動<T>參數
懲戒方法考慮以下情形:
我使用Silverlight和調用WCF服務。 Silverlight只能異步調用WCF服務。我爲WCF服務構建一個包裝,以便我可以使用Action參數。 (使客戶端代碼更清潔)。
所以我必須檢索會議室異步服務。
public interface IMeetingRoomService
{
void GetRooms(Action<List<MeetingRoom>> result);
}
將GetRooms變成List<MeetingRoom> GetRooms()
不是一個選項。
我想使用這項服務的視圖模型設置一個公共屬性名爲客房。
public class SomeViewModel
{
private readonly IMeetingRoomService _meetingRoomService;
public List<MeetingRoom> Rooms { get; set; }
public SomeViewModel(IMeetingRoomService meetingRoomService)
{
this._meetingRoomService = meetingRoomService;
}
public void GetRooms()
{
// Code that calls the service and sets this.Rooms
_meetingRoomService.GetRooms(result => Rooms = result);
}
}
我想單元測試SomeViewModel.GetRooms()的實現。 (對於這個問題,我很快就寫了實現,但實際上,我嘗試使用TDD。)
如何完成這個測試? 我正在使用NUnit和Moq。
[Test]
public void GetRooms_ShouldSetRooms()
{
var theRooms = new List<MeetingRoom>
{
new MeetingRoom(1, "some room"),
new MeetingRoom(2, "some other room"),
};
var meetingRoomService = new Mock<IMeetingRoomService>();
//How do I setup meetingRoomService so that it gives theRooms in the Action??
var viewModel = new SomeViewModel(meetingRoomService.Object);
viewModel.GetRooms();
Assert.AreEqual(theRooms, viewModel .Rooms);
}
編輯:
解決方案
閱讀斯蒂芬的回答第一。
這是測試代碼,我最後寫感謝斯蒂芬的回答是:
[Test]
public void GetRooms_ShouldSetRooms()
{
var meetingRoomService = new Mock<IMeetingRoomService>();
var shell = new ShellViewModel(meetingRoomService.Object);
var theRooms = new List<MeetingRoom>
{
new MeetingRoom(1, "some room"),
new MeetingRoom(2, "some other room"),
};
meetingRoomService
.Setup(service => service.GetRooms(It.IsAny<Action<List<MeetingRoom>>>()))
.Callback((Action<List<MeetingRoom>> action) => action(theRooms));
shell.GetRooms();
Assert.AreEqual(theRooms, shell.Rooms);
}
我會返回一個任務'' –
CodesInChaos
ehhh .....什麼? –