Role based X++ tests for D365FO

In my session about unit tests in D365FO in Lisbon in the Finance and Supply Chain Summit I hadn’t enough time to show this didactic example of how to make tests using a specific role or set of roles. So, below you’ll find the code example as well as a short explanation and video.

Step by Step:

This is the code example:

[SysTestSecurity('Manolo', [roleStr(SystemExternalUser)], true)]
final class FSCMSummitProofOfSysTestSecurity extends SysTestCase
{
	public void testSecurityManolo()
    {
        BankAccountTable bankAccountTable;

        this.parmExceptionExpected(true);
        bankAccountTable.IBAN = 'asdfasdf';
    }

    public void testSecurityAdmin()
    {
        SysTestSecurityScope securityScope = SysTestSecurityContext::setCurrentPersona('Admin');
        
		BankAccountTable bankAccountTable;
		bankAccountTable.IBAN = 'asdfasdf';

        securityScope.Dispose();

        this.parmExceptionExpected(true);
        bankAccountTable.IBAN = 'asdfasdf';
    }

}

We use the SysTestSecurity attribute to create a “Persona” with a particular set of roles. Our tests are done with the rights of that “Persona” (it will be used by default if we pass the third parameter as true). You can also change the “Persona” during the test execution using the SysTestSecurityContext::setCurrentPersona method, and it will give you back a SysTestSecurityScope instance that you can use to go back to the previous “Persona” using the method Dispose. This particular example is based in the fact that IBAN field in the BankAccountTable has the AOSAuthorization property set to yes, and so any user which roles don’t specifically grant access to the field (in our case we use the SystemExternalUser) it’s going to receive an exception when it tries to use that field. Hope it is helpful or at least interesting!


Leave a comment