2

I have a junction object with two master detail relationships. One to contacts and one to a custom object named program. I created the following trigger to avoid duplicates but im having A LOT of trouble with the testing part. Can someone tell me what could the test code for this trigger be? Thank you

trigger insert_case on Affiliated_Programs__c (before insert, before update) {
  for (Affiliated_Programs__c ci : trigger.new) {

//Checks the database for all affiliated programs with the same program and contact
  List<Affiliated_Programs__c> resultList = [SELECT id, Name FROM Affiliated_Programs__c
  WHERE Contact__c = :ci.Contact__c
  AND Program__c = :ci.Program__c];

// Raise the error back if any records found
   if (!resultList.isEmpty()) {
      System.debug('Found another copy ' + resultList[0].id + ' name is ' + resultList[0].Name);
      ci.addError('Duplicate record, a Contact is already related to that program');
   }
 }
}
3

Notice that you could solve the junction unique avoiding apex code using this

Having say that, this is a trivial example of how could be your trigger test:

@isTest(SeeAllData=true)
public class basicTests{

    @isTest static void runTests(){
        system.debug('starting tests...');
        test.startTest();     

        A__c a = new A__c(Name='test-trigger-a');
        B__c b = new B__c(Name='test-trigger-b');

        C__c c = new C__c(Name='test-trigger-c',ChildOfB__c = b.id,ChildOfA__c = a.id);
        C__c c2 = new C__c(Name='test-trigger-c2',ChildOfB__c = b.id,ChildOfA__c = a.id);
        try{
            insert c;
            insert c2;
            //fail!
            System.assert(false);
        }catch(System.DmlException e){
            System.assert(true);
        }

        test.stopTest();

    }    

}
| improve this answer | |
  • Thank you martin for both suggestions. Both worked and I got a better understanding of trigger tests! – Ricardo Jun 14 '13 at 20:40
0

If by avoiding duplicates, you mean no two junction objects can have the same two parents, then you should try searching across the stack: How to apply uniqueness on Junction object?

| improve this answer | |
  • Because I was using an apex trigger and I wanted to learn how test methods work. Thank you for your contribution. – Ricardo Jun 14 '13 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.