0

一意のアセット名のトリガーを作成しました。テスト ケースを作成する必要があります。apex を初めて使用するので、誰か助けてください。

Asset で NameTrigger をトリガーする (挿入前)

{

リストアル=新しいリスト();

al = [アセットから名前を選択];

if(Trigger.isInsert)

{

 For(integer i=0;i<al.size();i++)

 {

   for(Asset a2 : Trigger.New)

     {

       if(al[i].Name == a2.Name)

         {

           a2.Name.addError('This value already Exist');

         }

     }

 }

}

}

4

1 に答える 1

1

トリガーのテスト クラスは次のようになります。

@isTest
private class AssetTriggerTest {

    private static string assetName = 'TestAsset';
    private static Id accId;

    private static void createAccount(){
        Account acc = new Account(name='TestAcc');
        insert acc;
        accId = acc.Id;
    }

    private static Asset createAsset(){
    if(accId == null)
            createAccount();
        return new Asset(Name=assetName, AccountId=accId);
    }

    private static testMethod void testSingleInsert(){
        insert createAsset();

        List<Asset> assets = [SELECT Id FROM Asset WHERE Name = :assetName];
        system.assertEquals(1, assets.size());
    }

    private static testMethod void testInsertExistingName(){
        insert createAsset();

        Exception e;
        try{
            insert createAsset();
        } catch(Exception ex){
            e = ex;
        }

        system.assertNotEquals(null, e);
        system.assert(e instanceOf system.Dmlexception);
        system.assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));
        system.assert(e.getMessage().contains('This name is already used'));
    }

    private static testMethod void testDoubleInsertSameName(){

        Exception e;
        try{
            insert new List<Asset>{createAsset(), createAsset()};
        } catch(Exception ex){
            e = ex;
        }

        system.assertNotEquals(null, e);
        system.assert(e instanceOf system.Dmlexception);
        system.assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));
        system.assert(e.getMessage().contains('This name is already used'));

    }

}

クラスは、トリガーが有効なデータの保存を停止しないこと、および重複の作成を確実に停止しないことをテストします。Trigger.newコレクション内にも重複がある場合、データが保存されないように見える3番目のテストも追加しました。あなたのトリガーは現在これに対応していないので、3 つのテストすべてに合格するためにこのトリガーを正しくする方法のコピーを含めました。遠慮なく無視してください。

trigger AssetTrigger on Asset (before insert) {

    Map<string, Asset> newAssets = new Map<string, Asset>();
    for(Asset a : Trigger.new){
        if(!newAssets.containsKey(a.Name))
            newAssets.put(a.Name, a);
        else
            a.Name.addError('This name is already used');
    }

    for(Asset a : [SELECT Name FROM Asset WHERE Name IN :newAssets.keySet()]){
        newAssets.get(a.Name).Name.addError('This name is already used');
    }

}
于 2012-06-12T19:32:59.800 に答える