我有一個方法,調用一個服務來檢索一個對象的實例,更新實例,然後將實例保存回服務(代碼如下)。在模擬檢查更新的實例
我想知道的是,如果在起訂量一個很好的方法來檢查以下內容: -
- 也正在被保存回服務實例的原始實例 的修改版
- 該實例已更新爲所需
我知道我可以使用It.Is<MyThing>(x => x.Name == newName)
檢查這裏點2。儘管如此,忽略了第1點。
有沒有一種乾淨的方式來實現這一目標?
類代碼:
public class MyClass
{
private readonly IThingService thingService;
public MyClass(IThingService thingService)
{
this.thingService = thingService;
}
public void SaveMyThing(MyThing myThing)
{
var existingThing = thingService.Get(myThing.Id);
existingThing.Name = myThing.Name;
thingService.Save(existingThing);
}
}
public class MyThing
{
public int Id { get; set; }
public string Name { get; set; }
}
public interface IThingService
{
MyThing Get(int id);
void Save(MyThing myThing);
}
TEST CODE:
[Test]
public void Save_NewName_UpdatedThingIsSavedToService()
{
// Arrange
var myThing = new MyThing {
Id = 42,
Name = "Thing1"
};
var thingFromService = new MyThing
{
Id = 42,
Name = "Thing2"
};
var thingService = new Mock<IThingService>();
thingService
.Setup(ts => ts.Get(myThing.Id))
.Returns(thingFromService);
thingService
.Setup(ts => ts.Save(**UPDATED-THING-FROM-SERVICE**))
.Verifiable();
var myClass = new MyClass(thingService.Object);
// Act
myClass.SaveMyThing(myThing);
// Assert
thingService.Verify();
}
太棒了!我期望「thing == thingFromService」返回false爲「thing.Name!= thingFromService.Name」。事實並非如此,因爲thingFromService是在測試方法中更新的對象,因此是相同的。這是漫長的一天;-)謝謝傑夫! – 2010-02-22 18:28:26