场景
我在PreviewService.AddPreview中有方法。我想测试它是否添加新的预览。我使用C#和EntityFremework。如何通过自动增量编程测试以创建预览ID?我知道我应该拥有存储库或DAO,但我无权对其进行重构:(。
代码
private DbSet<WebsitePreview> _previewDbSet;
private List<WebsitePreview> _previews;
private IQueryable<WebsitePreview> _previewsAsQueryable => this._previews.AsQueryable();
在设置中
_previews = new List<WebsitePreview>();
_previewDbSet = A.Fake<DbSet<WebsitePreview>>(cat =>
cat.Implements<IQueryable<WebsitePreview>>());
A.CallTo(() => ((IQueryable<WebsitePreview>)_previewDbSet).Provider)
.Returns(_previewsAsQueryable.Provider);
A.CallTo(() => ((IQueryable<WebsitePreview>)_previewDbSet).GetEnumerator())
.Returns(_previewsAsQueryable.GetEnumerator());
A.CallTo(() => ((IQueryable<WebsitePreview>)_previewDbSet).Expression)
.Returns(_previewsAsQueryable.Expression);
A.CallTo(() => ((IQueryable<WebsitePreview>)_previewDbSet).ElementType)
.Returns(this._previewsAsQueryable.ElementType);
A.CallTo(() => _dbContext.Set<WebsitePreview>()).Returns(_previewDbSet);
测试
//arrange
string newPreviewName = "new";
WebsitePreview existingPreview = GetExistingPreview(); //it has id=1
this._previews.Add(existingPreview);
PreviewItemDto expectedPreviewItemDto = new PreviewItemDto
{
Id = 2,
Name = "new",
Selected = false
};
//act
var result = this._sut.AddNewPreview(newPreviewName);
//assert
//(2, 0)
Assert.AreEqual(expectedPreviewItemDto.Id, result.Id); //result.Id equals 0, expected 2