Home > Software design >  How can I setup linq for unit testing
How can I setup linq for unit testing

Time:10-30

I have created bellow method but now I want to unit test it. But I don't know how to set up linq query in my test.

     public async Task<Item> GetItemById(Guid Id)
        {
            var Item= await _userDbContext.Items.Where(c => c.Id.Equals(Id)).FirstOrDefaultAsync();
            return Item;
        }
[Test]
        public async Task GetItemById_Should_Retrieve_Item_Data()
        {
            // Arrange
            var itemId = Guid.NewGuid();
            var itemRecord = _fixture.Build<Item>().With(x => x.Id, itemId)
                .With(x => x.Item,item)
                .Create();
            //how can i setup my where linq query
           `**_userDBContextMock.Setup(x => x.Items).Returns(patientRecord);**`

            // Act 
            var result = await _appCrudRepository.GetItemById(itemId);

            // Assert
            result.Should().NotBeNull();
            result.Should().Be(itemRecord);
        }

CodePudding user response:

You should be mocking out your _appCrudRepository and the GetItemByID method specifically:

//Your implemenation here.
Mock<IAppCrudRepository> _appCrudRepository = new Mock<IAppCrudRepository>();

var itemRecord = _fixture.Build<Item>().With(x => x.Id, itemId)
                .With(x => x.Item,item)
                .Create();

_appCrudRepository.Setup(d => d.GetItemByID())
                .ReturnsAsync(itemRecord);

Now when you call GetItemByID it will return itemRecord.

  • Related