我有一个方法,调用一个服务来检索一个对象的实例,更新实例,然后将实例保存回服务(代码如下)。在模拟检查更新的实例
我想知道的是,如果在起订量一个很好的方法来检查以下内容: -
- 也正在被保存回服务实例的原始实例 的修改版
- 该实例已更新为所需
我知道我可以使用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