Base solution for your next web application
Open Closed

Unit test failing because AbpSession.UserId is NULL #7045


User avatar
0
firnas created

AbpSession.UserId is null when running unit tests. Is there a way i can set the user id in the unit test? I am mocking my App service for testing


4 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    Call LoginAsDefaultTenantAdmin or

    //Mock session
    Var session = Substitute.For<IAbpSession>();
    session.TenantId.Returns(1);
    session.UserId.Returns(1);
    LocalIocManager.IocContainer.Register(Component.For<IAbpSession>().Instance(session));
    
  • User Avatar
    0
    firnas created

    Both the ways did not work.

    Below is the unit testing code,

    LoginAsDefaultTenantAdmin();
    
                //arrange
                var mockBusinessDomainService = new Mock<IBusinessDomainService>();
                mockBusinessDomainService.Setup(b => b.GetBusinessFromUser(It.IsAny<long>()))
                    .ReturnsAsync(new Business.Business
                    {
                        BusinessName = "Test Business",
                        SubscriptionStatus = Enums.SubscriptionStatus.Subscribed.ToString()
                    });
                mockBusinessDomainService.Setup(b => b.UpdateBusiness(It.IsAny<string>(), It.IsAny<Business.Business>()))
                    .ReturnsAsync(new Business.Business
                    {
                        BusinessName = "Test Business",
                        SubscriptionStatus = Enums.SubscriptionStatus.UnSubscribed.ToString()
                    });
    
    
                IBusinessAppService _businessAppService = new BusinessAppService(
                    mockBusinessDomainService.Object,
                    Resolve<IObjectMapper>(),
                    Resolve<IUnitOfWorkManager>(),
                    Resolve<SignInManager>()
                    );
    
                //act
                Task t = _businessAppService.CancelSubscription();
    

    Below is part of the method,

    //check for user
                long userId = AbpSession.UserId.GetValueOrDefault();
    
                if (userId == 0)
                {
                    throw new UnauthorizedAccessException();
                }
    

    The user id is always 0. That is the problem.

  • User Avatar
    0
    maliming created
    Support Team

    Because AbpSession is property injection, it is best to use dependency injection.

    If you do this directly new a BusinessAppService. You can try _businessAppService.AbpSession = new Mock<IAbpSession>, etc.

  • User Avatar
    0
    firnas created

    Thanks for the response. I will change accordingly and test.