force.com salesforceでのセキュリティー 共有設定のテストについて

前提

ロール階層を使用したレコードレベルセキュリティーをテストします。

組織のデフォルトで顧客カスタムオブジェクトを非公開


これで、システム管理者以外のユーザは自身の所有する顧客レコード以外にアクセスできなくなる。

ロール階層(AdminRoleの配下にNormalRoleがある)


これで、AdminRoleを付与されたユーザはNormalRoleを付与されたユーザの所有するレコードにアクセスできるように制限が緩和される。

ユーザ


securityneko@gmail.com(システム管理者)とsecuritynekoodu@gmail.comユーザが存在する。

顧客レコード

テストコード

@isTest
private class SecurityTest {
	
	public static testMethod void testRunAs() {
    	
    	// 通常全てのApexコードはシステムモードで実行される
		System.debug('Current User: ' + UserInfo.getUserName());
		List<customer__c> cs = [select id from customer__c];	
		System.assertEquals(2,cs.size());
		
		// 1つ目と同じだが、明示的にシステム管理者ユーザを指定して実行みる
		User admin = [select id from User where username = 'securityneko@gmail.com'];
		System.runAs(admin) {
	        System.debug('Current User: ' + UserInfo.getUserName());
			List<customer__c> cs1 = [select id from customer__c];	
			System.assertEquals(2,cs1.size());
		}
		
		// ここはNormalRoleのsecuritynekoodu@gmail.comユーザで実行される
		User odu = [select id from User where username = 'securitynekoodu@gmail.com'];
		System.runAs(odu) {
	        System.debug('Current User: ' + UserInfo.getUserName());
			List<customer__c> cs2 = [select id from customer__c];	
			System.assertEquals(1,cs2.size());
		}
	
		//ロールを入れ替えてみる
		UserRole roleA = [select id from UserRole where name = 'AdminRole'];
		odu.UserRoleId = roleA.id;
		update odu;
		UserRole roleN = [select id from UserRole where name = 'NormalRole'];
		admin.UserRoleId = roleN.id;
		update admin;
		
		// さっきは1件のみ取得だったが、今回は2件取得できる
		System.runAs(odu) {
	        System.debug('Current User: ' + UserInfo.getUserName());
			List<customer__c> cs2 = [select id from customer__c];	
			System.assertEquals(2,cs2.size());
		}
	}
}

Apexコードは通常システムモードで起動しますがrunAs()の中では引数のユーザモードで実行されます。よって上述のように、securitynekoodu@gmail.comユーザで実行した場合は取得できる顧客レコードは1件になります。ロールを入れ替えることによりsecuritynekoodu@gmail.comユーザーにAdminRoleが付与され、securityneko@gmail.comユーザーがNormalRoleとなるとsecuritynekoodu@gmail.comユーザーでも取得できる顧客レコードは2件となるのが分かると思います。


レコードの共有ルールのテストはこのようにして作成できるのですが、オブジェクトレベルや項目レベルセキュリティーのチェックはできません。