0

Scenario

I have method in PreviewService.AddPreview. I would like to test it whether it add new Preview or not. I use C# and EntityFremework. How to program test to create id of Preview with autoincrementation? I know that I should have repository or DAO, but I have no permission to refactor it :(.

Code

private DbSet<WebsitePreview> _previewDbSet;
private List<WebsitePreview> _previews;
private IQueryable<WebsitePreview> _previewsAsQueryable => this._previews.AsQueryable();  

In Set Up

_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);

Test

//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
zolty13
  • 1,943
  • 3
  • 17
  • 34
  • Sorry, zolty13, but there isn't enough here for me to help. I'm not familiar with EntityFramework, and there are just not enough details in the question to help me guide you to a solution. If you could provide a complete, minimal failing test, I might be able to help, but as it is, I have no idea what `AddNewPreview` does or why you'd expect it to supply the right ID. But if you fill in the details, there's a chance. – Blair Conrad Aug 03 '18 at 15:50
  • Alternatively (additionally?), describe what you've tried. When you debug into the test, what do you see? Does `AddNewPreview` have find the existingPreview? If not, what does it find? At all stages, I would verify that the objects you encounter in your debugging session are the ones you expect (use `ReferenceEquals` to check). – Blair Conrad Aug 03 '18 at 16:30
  • Hi, according to id I tried nothing. I just Wonder how to fake id in my entity, when I add it to collection. – zolty13 Aug 06 '18 at 07:17
  • Hi, according to id I tried nothing. I just Wonder how to fake ID in my entity, when I add it to collection. I want to simulate bahaviour of Data Base. – zolty13 Aug 06 '18 at 07:33

0 Answers0