Open Closed

XUnit test case -Not able to mock the repository #5515


User avatar
0
mithun created

We are using ABP commercial version and have a requirement to write XUnit test cases.

ABP Framework version: v7.2.2 UI type: Blazor Server Side DB provider: EF Core Tiered (MVC): yes

  • Exception message and full stack trace:
  • Steps to reproduce the issue: Not able to mock the repository which is using in API endpoint.
public async Task<bool> CheckSLevelAsync(int hId, int pId)  ==> API endpoint
{
        var result = _hRepository.FirstOrDefaultAsync(x => x.HId == hId && x.PId == pId).Result;
        if (result != null)
        {
            return true;
        }
        return false;
    }

Can you help us how to mock the repository and setup the expected result


5 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    ABP has a lot of unit test code, you can refer to:

    https://github.com/abpframework/abp/tree/dev/framework/test https://github.com/abpframework/abp/tree/dev/modules/cms-kit/test

  • User Avatar
    0
    mithun created

    Thanks for the response, will refer the links.

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    ok

  • User Avatar
    0
    mithun created

    Hi can you please provide a simple sample example for my requirement. public async Task CheckSLevelAsync(int hId, int pId) ==> My API endpoint { var result = _hRepository.FirstOrDefaultAsync(x => x.HId == hId && x.PId == pId).Result; if (result != null) { return true; } return false; } I want to mock the "_hRepository" and want to write xunit test cases. Can you pls. provide sample code how to mock the repository and run a xunit test case.

  • User Avatar
    0
    jfistelmann created

    something like this?

    /* This is just an example test class.
     * Normally, you don't test ABP framework code
     * Only test your custom repository methods.
     */
    public class SampleRepositoryTests : FastNFunEntityFrameworkCoreTestBase
    {
        private readonly IRepository<IdentityUser, Guid> _appUserRepository;
    
        public SampleRepositoryTests()
        {
            _appUserRepository = GetRequiredService<IRepository<IdentityUser, Guid>>();
        }
    
        [Fact]
        public async void ShouldQueryAppUser()
        {
            /* Need to manually start Unit Of Work because
             * FirstOrDefaultAsync should be executed while db connection / context is available.
             */
            await WithUnitOfWorkAsync(async () =>
            {
                //Act
                var adminUser = await _appUserRepository
                .FirstOrDefaultAsync(u => u.UserName == "admin");
    
                //Assert
                adminUser.ShouldNotBeNull();
            });
        }
    }
    
Made with ❤️ on ABP v9.1.0-preview. Updated on December 12, 2024, 07:15