最近我一直在努力改进我的单元测试,而真正让我困惑的 UT 的“规则”之一是“每个测试一个断言”。
我很想知道人们是否认为 MS 在断言这个测试方面做了正确的事情(忽略缺少模拟等)。根据我目前的理解,这个示例实际上应该为每个需要测试的对象属性执行一个创建调用(而不是一个调用和多个断言)。我做出这个假设是否正确?
方法取自:http: //msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3testing_topic4
[TestMethod()]
[DeploymentItem("MvcMusicStore.mdf")]
[DeploymentItem("MvcMusicStore_log.ldf")]
public void CreateTest()
{
using (TransactionScope ts = new TransactionScope())
{
StoreManagerController target = new StoreManagerController();
Album album = new Album()
{
GenreId = 1,
ArtistId = 1,
Title = "New Album",
Price = 10,
AlbumArtUrl = "/Content/Images/placeholder.gif"
};
ActionResult actual;
actual = target.Create(album);
Assert.IsTrue(album.AlbumId != 0);
MusicStoreEntities storeDB = new MusicStoreEntities();
var newAlbum = storeDB.Albums.SingleOrDefault(a => a.AlbumId == album.AlbumId);
Assert.AreEqual(album.GenreId, newAlbum.GenreId);
Assert.AreEqual(album.ArtistId, newAlbum.ArtistId);
Assert.AreEqual(album.Title, newAlbum.Title);
Assert.AreEqual(album.Price, newAlbum.Price);
Assert.AreEqual(album.AlbumArtUrl, newAlbum.AlbumArtUrl);
}
}
按版本将类似于(为专辑对象上的每个属性复制)
[TestMethod()]
public void CreateTest_AlbumUrl()
{
// ** Arrange
var storeDB = new Mock<MusicStoreEntities>()
// Some code to setup the mocked store would go here
StoreManagerController target = new StoreManagerController(storeDB);
Album album = new Album()
{
GenreId = 1,
ArtistId = 1,
Title = "New Album",
Price = 10,
AlbumArtUrl = "/Content/Images/placeholder.gif"
};
// ** Act
actual = target.Create(album);
var newAlbum = storeDB.Albums.SingleOrDefault(a => a.AlbumId == album.AlbumId);
// ** Assert
Assert.AreEqual(album.AlbumArtUrl, newAlbum.AlbumArtUrl);
}