0

I have written a trigger for unique asset name.I have to write a test case for it can someone please help I am new to apex.

trigger NameTrigger on Asset (before insert)

{

list al = new List ();

al = [select Name from Asset];

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集合中也存在重复数据,则不会保存数据。您的触发器目前不适合这种情况,因此我提供了一份副本,说明我将如何纠正此触发器以通过所有三个测试;随意忽略。

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 回答