Search code examples
exception.net-coremockingxunit

Throw exception and getting it in assert of xunit in .net


I want to test this method

    public async Task<GetLayoutResponse> Handle(GetLayoutQuery request, CancellationToken cancellationToken)
    {
        string ravenId = UserLayout.GetId(_userService.CustomerIsin);
        var cRepository = CacheableRepository<UserLayout>.From(_repository);
        var res = await cRepository.GetAsync(ravenId);
        if (!res.IsSucceeded)
            throw new EasyException(EasyException.DATABASE_EXCEPTION, "DatabaseException");
        return new GetLayoutResponse { LayoutModel=res?.Data?.LayoutModel };
    }

As you can see in this part throw new EasyException(EasyException.DATABASE_EXCEPTION, "DatabaseException"); I throw an exception . So here is my test code :

    [Fact]
        public async void GetLayoutQueryTestException()
        {
            //Arrange

            var data = new domain.Entities.UserLayout() { CreateDateTime=DateTime.Now, Id= $"{nameof(UserLayout)}/", LayoutModel="MyLayout" };

            var mediator = new Mock<IMediator>();
            var userservice = new Mock<ICurrentUserService>();

            var repoacc = new Mock<IRepositoryAccessor>();
            var repo = new Mock<domain.Interfaces.IRepository<UserLayout>>();

            repoacc.Setup(i => i.GetRepository<UserLayout>(It.IsAny<string>(), It.IsAny<DatabaseType>(), It.IsAny<Type>(), It.IsAny<bool>(), It.IsAny<bool>())).Returns(repo.Object);
            repo.Setup(i => i.GetByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(OperationResult<UserLayout>.Failed(EasyException.DATABASE_EXCEPTION.ToString())));



            GetLayoutQuery command = new GetLayoutQuery();
            GetLayoutQueryHandler handler = new GetLayoutQueryHandler(userservice.Object, repoacc.Object);
            //Act
            var x = await handler.Handle(command, new System.Threading.CancellationToken());
       
            //Assert

          

            Assert.IsType<EasyException>(x);
}

But my test code can't detect the exception and returns this error:

 easy.api.tests.LayoutTests.LayoutResponseTests.GetLayoutQueryTestException
   Source: LayoutResponseTests.cs line 89
   Duration: 272 ms

  Message: 
domain.Exceptions.EasyException : DatabaseException

  Stack Trace: 
GetLayoutQueryHandler.Handle(GetLayoutQuery request, CancellationToken cancellationToken) line 33
LayoutResponseTests.GetLayoutQueryTestException() line 109
<>c.<ThrowAsync>b__127_0(Object state)

Solution

  • Finally :

    var caughtException =await Assert.ThrowsAsync<EasyException>(() => handler.Handle(command, new System.Threading.CancellationToken()));
    Assert.Equal("DatabaseException", caughtException.Message);