トリガーのテスト クラスは次のようになります。
@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');
}
}