使用 Nunit 和 Moq 对某个操作是否根据用户类型启用或禁用进行单元测试

问题描述 投票:0回答:1

我在 XAF 中使用 ViewActionController 创建了一个操作。根据用户类型从 OnActivated() 方法启用此操作。

public VehicleFileAnalyzerController()
        {
            InitializeComponent();
            TargetObjectType = typeof(ABCInfo);
            {
                ABCAction= new(this, "ABCModule", PredefinedCategory.Edit)
                {
                    SelectionDependencyType = SelectionDependencyType.Independent
                };
                ABC.Execute += ABC_Execute;
            }
        }

 protected override void OnActivated()
        {
            base.OnActivated();
            var user = SecuritySystem.CurrentUser as OAuthPermissionUser;
            bool isAdminRole = user.IsAdmin;
            bool isDealerRole = user.IsDealer;
            bulkUploadAction.Active.SetItemValue("Active", (isAdminRole || isDealerRole));
        }

我需要测试此操作是否仅对管理员和经销商有效,不适用于其他类型的用户。

我创建了一个 Nunit 测试并尝试了这个

      [TestCase(true, false, false)]    // Admin
        [TestCase(false, true, true)]   // Dealer only
        public void Test_ActionEnabledForUserType(bool isAdmin, bool isDealer, bool expectedEnabled)
        {
            // Set up the mock application and object space
            controller = new ABCController();
            mockApplication = new Mock<XafApplication>();
            mockApplication.CallBase = true;
            controller.Application = mockApplication.Object;
            ABCAction = GetPrivateField<SimpleAction>(controller, "ABC");
            mockObjectSpace = new Mock<IObjectSpace>();
            ModuleList moduleList = new ModuleList {
                new ABCModule()
                };
            var entityStoreMock = new Mock<IEntityStore>();
            var objectSpaceProviderMock = new Mock<IObjectSpaceProvider>();
            objectSpaceProviderMock.Setup(o => o.EntityStore).Returns(entityStoreMock.Object);

            ExpressApplicationSetupParameters setupParameters = new ExpressApplicationSetupParameters(null, objectSpaceProviderMock.Object, new ControllersManager(), moduleList);
            mockApplication.Object.Setup(setupParameters);

错误出现在以下几行中,我试图设置用户 `

var mockCurrentUser = new Mock<OAuthPermissionUser>();

             mockCurrentUser.SetupGet(u => u.IsAdministrator).Returns(isAdmin);
             mockCurrentUser.SetupGet(u => u.IsDealer).Returns(isDealer);

            Assert.That(expectedEnabled, Is.EqualTo(ABCAction.Active["Active"]));

它抛出错误作为不支持的表达式:u => u.IsAdministrator

我也尝试像下面这样分配

            var user = new OAuthPermissionUser(session);
            user.IsAdministrator = isAdmin;
            user.IsDealer = isDealer;

但它不会改变属性的值。

OAuthPermissionUser 类如下

public class OAuthPermissionPolicyUser : PermissionPolicyUser, IObjectSpaceLink, IXafEntityObject, ISecurityUserWithLoginInfo
    {
        public OAuthPermissionUser(Session session) : base(session) { }

        [PersistentAlias("Roles[Name == 'Administrators'].Exists()")]
        public bool IsAdministrator
        {
            get
            {
                administrator = (bool)EvaluateAlias(nameof(IsAdministrator));
                return administrator;
            }
            set => SetPropertyValue(nameof(IsAdministrator), ref administrator, value);
        }

        [PersistentAlias("Roles[Name == 'Dealer'].Exists()")]
        public bool IsDealer
        {
            get
            {
                dealer= (bool)EvaluateAlias(nameof(IsDealer));
                return dealer;
            }
            set => SetPropertyValue(nameof(IsDealer), ref dealer, value);
        }
}

我猜,问题出在这行代码中。

[PersistentAlias("Roles[Name == 'Administrators'].Exists()")]

因为它在服务器端执行。有没有办法在单元测试时设置用户类型(管理员或经销商)?

c# nunit moq xaf
1个回答
0
投票

Moq(和其他动态交互测试库)只能重新定义可重写的内容。尝试将属性公开:

[PersistentAlias("Roles[Name == 'Administrators'].Exists()")]
public virtual bool IsAdministrator
// ...

[PersistentAlias("Roles[Name == 'Dealer'].Exists()")]
public virtual bool IsDealer
// ...

不过,总的来说,您可能需要重新考虑设计。从概念上讲,属性是,为什么要使值可重写?

替代设计看起来更合适(并且更惯用):

var user = new OAuthPermissionUser(session);
user.IsAdministrator = isAdmin;
user.IsDealer = isDealer;

您写道这不会改变属性的值。如果这样的代码不起作用,你可能会遇到比测试更大的问题,所以我会首先调查一下。

© www.soinside.com 2019 - 2024. All rights reserved.