function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
GorkyGorky 

Try to simulate object pass by trigger.new on a TestMethod

Hello Everybody,

I'm really newby whit Apex, this is my first testMethod and I'm stuck with this. Maybe anyone can help me?

The method I want to test called checkOrder waits for a Opportunity object who is sent by a call in a  before update trigger.
I try to simulate this on my testMethod but obviously I'm not doing this well 'cause in the call to checkIntranetOrder inside my test method the for condition never begins.

What I'm doing wrong? What is the way to simulate the pass of a Opportunity  object as sent by a trigger.new or trigger.old?

Thanks in advance

The code:

   public static testMethod void TestcheckIntranetOrder() {
        Opportunity[] lOp = [Select Id,Order__c from Opportunity where Id = '006R000000286W2']; --> Make a Opportunity whit the values I need
       
chekOrder(lOp); --> Call chekOrder Method
    }

    public static void checkOrder(Opportunity[] accs){
         for (Opportunity a:accs){            --> Want a opportunity 
             if (a.Order__c!=NULL){   
                 a.addError('Alert');
            }        
         }
     }
}
ad75ad75
Hi Gorky.  I think that your problem might be that in your TestcheckIntranetOrder() method you need to instantiate a brand new Opportunity in your test method then insert that to the database.  At the moment it looks like your test method does not insert a new Opportunity, it just queries for existing ones.  As far as I know, instantiating a new opp in Apex code is not the same as inserting it into the database, and it's the database insertion that fires the trigger.

GorkyGorky
I made it!!

Using a <list>

List<Opportunity> leads = new List<Opportunity>();
leads.add(new Opportunity(Order__c='12332'));
checkOrder(leads);

Thanks ! :)
jrotensteinjrotenstein
The best way to simulate it is... not to simulate it at all!

In your TestMethod, you should actually create a new Object, then insert it. This will cause your trigger to activate. You should then do some tests (eg System.Assert) to check that your trigger code did what you expected.

The system will automatically roll-back the Object you created, since it was part of a TestMethod.

For an example, see the Testing section of the Introduction to Apex article.