I have written the test class for trigger in salesforce

private class DeliveryDateUpdationtest{
    static testMethod void DeliveryDateUpdation()

        account[] testaccount1 = new List<Account>();
        testAccount1.add(new Account(Name='Test',Type='Test',Status__c = 'Draft',Call_Status__c = 'called On',JDE_Date_Delivery_Offset__c = null));
        testAccount1.add(new Account(Name='Test1',Type='Test',Status__c = 'Draft',Call_Status__c = 'called On',JDE_Date_Delivery_Offset__c = 2.00));
        insert testAccount1;

        Product2 testProduct = new Product2(Name='Test', IsActive=true, CurrencyIsoCode = 'EUR');
        insert testProduct;

        Pricebook2 testPriceBook = new Pricebook2(Name='Test', IsActive=true,Shipment_Method__c = 'Internal',Market__c = 'FR');
        insert testPriceBook;

        PricebookEntry[] testPricebookEntries = new list<PricebookEntry>();
        testPricebookEntries.add(new PricebookEntry(Pricebook2Id=Test.getStandardPricebookId(), UnitPrice=4.99, Product2Id=testProduct.Id,CurrencyIsoCode = 'EUR'));
        testPricebookEntries.add(new PricebookEntry(Pricebook2Id=testPriceBook.Id, UnitPrice=4.99, UseStandardPrice=false, Product2Id=testProduct.Id,CurrencyIsoCode = 'EUR'));
        insert testPricebookEntries;

        order[] order1 = new list<order>();
        order1.add(new Order(AccountId = testAccount1[0].id, EffectiveDate = date.newinstance(2017, 3, 29) ,Status = 'Draft',Shipping_Urgency__c = 'high',Subtype__c = 'offer',Pricebook2Id=testPriceBook.Id,OrderDeliveryDate__c = date.newinstance(2017, 3, 10)));
        order1.add(new Order(AccountId = testAccount1[0].id, EffectiveDate = date.newinstance(2017, 3, 29) ,Status = 'Draft',Shipping_Urgency__c = 'high',Subtype__c = 'offer',Pricebook2Id=testPriceBook.Id,OrderDeliveryDate__c = date.newinstance(2017, 3, 11)));
        order1.add(new order(AccountId = testAccount1[0].id, EffectiveDate = Date.today(),Status = 'Draft',Shipping_Urgency__c = 'high',Subtype__c = 'ASP',Pricebook2Id=testPriceBook.Id,OrderDeliveryDate__c = date.newinstance(2017, 3, 10)));
        order1.add(new order(AccountId = testAccount1[1].id, EffectiveDate = Date.today(),Status = 'Draft',Shipping_Urgency__c = 'high',Subtype__c = 'ASP',Pricebook2Id=testPriceBook.Id,OrderDeliveryDate__c = date.newinstance(2017, 3, 11)));
        insert order1;

        Holiday__c[] holiday1 = new list<Holiday__c>();
        holiday1.add(new Holiday__c(Date__c = Date.today(),Country__c = 'FR'));
        holiday1.add(new Holiday__c(Date__c = Date.today(),Country__c = 'IT'));
        insert holiday1;

        OrderItem orderItemOffer = new OrderItem();
        orderItemOffer.PricebookEntryId = testPricebookEntries[1].Id;
        orderItemOffer.OrderId = order1[0].Id;
        orderItemOffer.Quantity = 2; 
        orderItemOffer.UnitPrice = 50; 
        orderItemOffer.Delivery_Date__c = date.newinstance(2017, 3, 10);
        insert orderItemOffer;

        orderItemOffer  = [select id, Delivery_Date__c from orderItem where Id = :orderItemOffer.Id];
        System.assertEquals(date.newinstance(2017, 04, 05), orderItemOffer.Delivery_Date__c);

        OrderItem orderItemOffer1 = new OrderItem();
        orderItemOffer1.PricebookEntryId = testPricebookEntries[1].Id;
        orderItemOffer1.OrderId = order1[1].Id;
        orderItemOffer1.Quantity = 2; 
        orderItemOffer1.UnitPrice = 50; 
        orderItemOffer1.Delivery_Date__c = date.newinstance(2017, 3, 10);
        insert orderItemOffer1;

        orderItemOffer1 = [select id, Delivery_Date__c from orderItem where Id = :orderItemOffer1.Id];
        System.assertEquals(date.newinstance(2017, 04, 05), orderItemOffer.Delivery_Date__c);

        OrderItem orderItemASP = new OrderItem();
        orderItemASP.PricebookEntryId = testPricebookEntries[1].Id;
        orderItemASP.OrderId = order1[2].Id;
        orderItemASP.Quantity = 2; 
        orderItemASP.UnitPrice = 50; 
        orderItemASP.Delivery_Date__c = date.newinstance(2017, 3, 10);
        insert orderItemASP;

        orderItemASP = [select id, Delivery_Date__c from orderItem where Id = :orderItemASP.Id];
        System.assertEquals(date.newinstance(2017, 04, 03), orderItemASP.Delivery_Date__c);

        OrderItem orderItemASP1 = new OrderItem();
        orderItemASP1.PricebookEntryId = testPricebookEntries[1].Id;
        orderItemASP1.OrderId = order1[3].Id;
        orderItemASP1.Quantity = 2; 
        orderItemASP1.UnitPrice = 50; 
        orderItemASP1.Delivery_Date__c = date.newinstance(2017, 3, 10);
        insert orderItemASP1;

        orderItemASP1 = [select id, Delivery_Date__c from orderItem where Id = :orderItemASP1.Id];
        System.assertEquals(date.newinstance(2017, 3, 10), orderItemASP1.Delivery_Date__c);

        OrderItem orderItemASP2 = new OrderItem();
        orderItemASP2.PricebookEntryId = testPricebookEntries[1].Id;
        orderItemASP2.OrderId = order1[3].Id;
        orderItemASP2.Quantity = 2; 
        orderItemASP2.UnitPrice = 50; 
        orderItemASP2.Delivery_Date__c = date.newinstance(2017, 3, 10);
        insert orderItemASP2;

        orderItemASP2 = [select id, Delivery_Date__c from orderItem where Id = :orderItemASP2.Id];
        System.assertEquals(date.newinstance(2017, 04, 03), orderItemASP2.Delivery_Date__c);


Trigger code:

trigger DeliveryDateUpdation on orderitem(before insert) {
    Map<Id, Order> orders = new Map<Id, Order>();
    for(OrderItem record: Trigger.new) {
        orders.put(record.OrderId, null);
    orders.putAll([SELECT Id,Account.JDE_Date_Delivery_Offset__c, OrderDeliveryDate__c,Subtype__c FROM Order WHERE Id =:orders.keySet()]);
    Set<String> markets = new Set<String>();
    for(Order record: orders.values()) {
        if(record.Subtype__c == 'Offer') {
        if(record.Subtype__c == 'ASP') {
    if(markets.size()<=0) {return;}
    Map<string, Map<Date,Holiday__c>> holidays = new Map<string, Map<Date,Holiday__c>>();
    for(String market: markets) {
        holidays.put(market, new Map<Date, Holiday__c>());
    for(Holiday__c record: [SELECT Date__c, Country__c FROM Holiday__c WHERE Country__c = :markets]) {
        holidays.get(record.Country__c).put(record.Date__c, record);
    Time midnight = Time.newInstance(0, 0, 0, 0);
    for(OrderItem record: Trigger.new) {
        Order orderRecord = orders.get(record.OrderId);
        if(orderRecord.OrderDeliveryDate__c  == record.Delivery_Date__c && (orderRecord.SubType__c == 'Offer'|| orderRecord.SubType__c == 'ASP')) 
            String market = orderRecord.SubType__c == 'Offer'? 'FR': 'IT';
            Date UpdatedDeliverydate = Date.today();
            integer Offsetvalue;
            if(orderRecord.Account.JDE_Date_Delivery_Offset__c!= null) {
                Offsetvalue = orderRecord.Account.JDE_Date_Delivery_Offset__c.intValue();
            if(orderRecord.Account.JDE_Date_Delivery_Offset__c == null && orderRecord.SubType__c == 'Offer') {
                Offsetvalue = 5;
            if(orderRecord.Account.JDE_Date_Delivery_Offset__c == null  && orderRecord.SubType__c == 'ASP') {
                Offsetvalue = 3;
            while(Offsetvalue > 0) {
                UpdatedDeliverydate = UpdatedDeliverydate.addDays(1);
                DateTime UpdatedDeliverydatetime = DateTime.newInstance(UpdatedDeliverydate , midnight);
                String dayName = UpdatedDeliverydatetime.format('EEEE');
                if(dayName != 'Saturday' && dayName != 'Sunday' && !holidays.get(market).containsKey(UpdatedDeliverydate)) {
                    Offsetvalue --; 
            if(orderRecord.OrderDeliveryDate__c < UpdatedDeliverydate)
                record.Delivery_Date__c = UpdatedDeliverydate;

While inserting the order and account it is showing error :

System.LimitException: Too many SOQL queries: 101

How to avoid this error?please anyone rectify

  • The problem comes from your trigger, not the test class. There must be some queries inside some for loops. – Martin Lezer Mar 29 '17 at 13:00
  • @MartinLezer there is no query inside the trigger code,please see my trigger code – Learning user Mar 29 '17 at 13:03
  • There must be other triggers which are fired automatically. – Martin Lezer Mar 29 '17 at 13:06
  • @MartinLezer My code does not have problem,shall i deploy the code from sandbox to production – Learning user Mar 29 '17 at 13:06
  • 1
    You could be having trigger on different object which might or might not have a query in a for loop. Avoid Recursive Trigger Calls. Best place to look at is debug logs – Raul Mar 29 '17 at 13:07

Congratulations, you're progressing as a developer, and have run into the next big wall that developers face. Pieces of your code are starting to interact with other pieces of your code. This is a powerful feature of programming in general, but, as they say, with great power comes great responsibility.

In this case, going over 100 SOQL queries indicates that you either didn't expect code (that is interacting) to interact, or that the interaction needs work (or possibly both).

Going forward, you'll need to start considering how your code interacts with other code (i.e. On trigger A, I call some code that updates a record of object B, which will cause trigger B to run, which then updates a record of object C, etc...).

You'll also need to start considering how other code will call and interact with the code you're currently developing (i.e. My code has a query in it, and I expect it to be called from a trigger. Therefore, my code should probably have an argument that accepts a List of objects instead of just an argument that accepts a single record).

I think you'll need to spend an amount of time looking through debug logs to figure this one out. The code you've provided doesn't seem to be the problem (at least, it's not the source of the problem), the query you've indicated just happens to be the one that put you over the limit.

I suppose that it could simply be that the setup that you're doing for your test (creating and inserting Account, Product2, Pricebook2, PricebookEntry, and Order records) requires just enough queries to put you over the limit (for which using startTest/stopTest would help)...but the amount of setup that you're doing doesn't look like it would be enough to cause issues. At any rate, looking through debug logs should help you figure out what's going on.

Looking through How do I start to debug my own Apex code? may help get you started.

Using Test.startTest(), and Test.stopTest() (you can read more about them through the documentation on the Test class) may help, but the fact that you're running into query limit issues is a red flag (an indication that something isn't as it should be).

Poring over debug logs is tedious work, but doing so gives you the best picture of what's actually happening (as opposed to what you think should be happening).

A few tips:

  • Start with debug levels all at DEBUG. Increase (FINE, FINER, FINEST) the log individual log levels to get more information about a specific aspect of the execution, or decrease (INFO, WARN, ERROR, NONE) a log level to decrease the size of the log file/remove things you aren't interested in from the debug log
  • The 'Analysis' perspective in the dev console can be a useful place to start
  • Pay attention to the order in which different pieces of code are executing. The debug log should tell you when Triggers, DML, and specific class methods start executing, and when they have finished executing.
  • If you see something (code, SOQL, etc... basically anything that isn't a validation or workflow rule) being executed over and over again, focus on it. Try to work out what is calling the code over and over, and why the caller is repeatedly calling that code. (e.g. A query is being called multiple times. It is part of method A, which is being called by a trigger. The trigger is calling method A multiple times because method A appears in a for loop that is iterating over trigger.new)
  • Keep in mind that workflow field updates can cause triggers to execute again
| improve this answer | |

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.