+ Start a Discussion
Akash Garg 2Akash Garg 2 

Test class failed while validate apex class

I have apex class against which test class has been written but while Run test it failed due to 1 errors at 3 levels in test

1. FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [SAP_Sales_Area_Number__c]
Attaching Apex class and test class. 
Help in correcting the test class.
 
public class OpportunityTriggerHandler extends TriggerHandler{

    protected override void beforeInsert(){
        setStandardPricebook();
        setRecordTypeFromLeadConversion();
        populateInfoFromSalesArea();
        distributorOpptyRecordType();
    }
    protected override void beforeUpdate(){        
        setStandardPricebook();//Change 0.2
        stampPlant();
        populateInfoFromSalesArea();      
    }
    protected override void afterInsert(){
    }
    protected override void afterUpdate(){
        updateTangible();
    }
    
    public void stampPlant(){        
        Set<Id> optySet = new Set<Id>();
        List<OpportunityLineItem> finaloptyLineItemList = new List<OpportunityLineItem>();
        for(Opportunity opty : (List<Opportunity>)Trigger.New)
        {           
            Opportunity o = (Opportunity)Trigger.oldMap.get(opty.Id);
            if(o.Plant__c != opty.Plant__c)
            {
                optySet.add(opty.Id);         
            }
        }
        
        if(optySet != null && !optySet.isEmpty())
        {
            List<OpportunityLineItem> optyLineItemList = new List<OpportunityLineItem>([Select Id, Plant__c, OpportunityId from OpportunityLineItem where OpportunityId IN:optySet]);
            for(OpportunityLineItem oli : optyLineItemList)
            {
                Opportunity o = (Opportunity)Trigger.newMap.get(oli.OpportunityId);
                oli.Plant__c = o.Plant__c;
                finaloptyLineItemList.add(oli);
            }
        }
        if(finaloptyLineItemList != null && !finaloptyLineItemList.isEmpty())
        {
            update finaloptyLineItemList;
        }
    }
   
    private void updateTangible(){
      
        List<Opportunity> listOpportunityTriggerNew ;
        Map<Id, Opportunity> oldMap ;
        Map<Id, Decimal> mapOpportunityIdToExpectedRevenueChanged ;
        List<Event> listEvent ;
        //Map<Id, List<Event>> mapOpportunityIdToListEvent ;
        Map<Id, Id> mapEventIdToOpportunityId ;
        List<Id> listTourPlanId ;
        Map<Id, Tour_Plan_TI__C> mapTourPlan ;
        final String eventRecordTypeName = 'Planned' ;

        mapOpportunityIdToExpectedRevenueChanged = new Map<id, Decimal>() ;
        listTourPlanId = new List<Id>() ;
        mapEventIdToOpportunityId = new Map<Id, Id>();

        listOpportunityTriggerNew = (List<Opportunity>)Trigger.New ;
        if(Trigger.isUpdate){ oldMap = (Map<Id, Opportunity>)Trigger.oldMap ; }

        for(Opportunity opportunityNew : listOpportunityTriggerNew){
            Decimal newExpectedRevenue;
            Decimal oldExpectedRevenue;
            newExpectedRevenue = (opportunityNew.ExpectedRevenue!=null)?opportunityNew.ExpectedRevenue:0.0;
            oldExpectedRevenue = ((oldMap.get(opportunityNew.Id)).ExpectedRevenue!=null)?(oldMap.get(opportunityNew.Id)).ExpectedRevenue:0.0;

            //Decimal expectedRevenueChange =  opportunityNew.ExpectedRevenue - (oldMap.get(opportunityNew.Id)).ExpectedRevenue ;
            Decimal expectedRevenueChange = newExpectedRevenue -oldExpectedRevenue ;
            if( expectedRevenueChange != Decimal.valueOf(0) ){
                mapOpportunityIdToExpectedRevenueChanged.put(opportunityNew.Id, expectedRevenueChange);
            }
        }

        if( !mapOpportunityIdToExpectedRevenueChanged.isEmpty() ){

            listEvent = [SELECT Id, WhatId, Opportunity_TI__c 
                            FROM Event
                            WHERE Opportunity_TI__c != null
                            AND Opportunity_TI__c IN :mapOpportunityIdToExpectedRevenueChanged.keySet()
                            AND Status_TI__c != 'Cancelled'
                            AND recordType.Name = :eventRecordTypeName];

            for(Event event : listEvent){
                listTourPlanId.add(event.WhatId);
                mapEventIdToOpportunityId.put(event.Id, event.Opportunity_TI__c) ;
            }

            mapTourPlan = new Map<Id,Tour_Plan_TI__C>([SELECT Id, Tangible__c
                            FROM Tour_Plan_TI__C
                            WHERE Id IN :listTourPlanId
                            ]);

            for(Event event : listEvent){
                if((mapTourPlan.get(event.WhatId)).Tangible__c == null){ (mapTourPlan.get(event.WhatId)).Tangible__c = 0.0 ; }
                (mapTourPlan.get(event.WhatId)).Tangible__c += mapOpportunityIdToExpectedRevenueChanged.get( mapEventIdToOpportunityId.get(event.Id) );
            }

            try{   update mapTourPlan.values();  }  catch(Exception e){ System.debug('Error in updating Tour plan tangible on updating opportunity'+e) ; }


        } //if ends

    }//update Tangible method ends

    private void populateInfoFromSalesArea(){

        List<Opportunity> listOpportunityWithSalesArea = new List<Opportunity>()  ;
        Set<Id> setAccountId = new Set<Id>();
        Set<Id> setSalesArea = new Set<Id>();
        Set<String> setSalesOrg = new Set<String>();
        Map<Id, Sales_Area__c> mapSalesArea = new Map<Id, Sales_Area__c>();

         for(Opportunity opportunity : (List<Opportunity>)Trigger.New){
        
            if( opportunity.Sales_Area__c!=null && opportunity.AccountId!=null){
                listOpportunityWithSalesArea.add(opportunity);
                setAccountId.add(opportunity.AccountId);
                setSalesArea.add(Opportunity.Sales_Area__c);
            }
         }

         mapSalesArea = new Map<Id, Sales_Area__c>([SELECT Id, VKORG__c, VTWEG__c, SPART__c, Division__c, Distribution_Channel__c, Sales_Org__c, Unique_Key__c
                                    FROM Sales_Area__c
                                    WHERE ID IN :setSalesArea 
                                        AND SPART__c!=NULL AND VTWEG__c!=NULL AND VKORG__c!=NULL
                                    ]);
         for(Sales_Area__c salesArea : mapSalesArea.values()){
            setSalesOrg.add(salesArea.VKORG__c);
         }

         if(!setSalesArea.isEmpty() && !setAccountId.isEmpty()){
            
            List<Sales_Area_TI__c> listAccountSalesArea = [SELECT Id, CurrencyISOCode, Account_Name__c, Payment_Terms__c, Price_List__c, Incoterms__c, SAP_Sales_Area_Number__c, Incoterms_2__c,
                                                                          SAP_Sales_Area_Number__r.SPART__c, SAP_Sales_Area_Number__r.VTWEG__c, SAP_Sales_Area_Number__r.VKORG__c, SAP_Sales_Area_Number__r.Unique_Key__c      
                                                                FROM Sales_Area_TI__c
                                                                WHERE Account_Name__c IN :setAccountId AND ( SAP_Sales_Area_Number__c IN :setSalesArea OR SAP_Sales_Area_Number__r.VKORG__c IN :setSalesOrg)
                                                                AND Payment_Terms__c!=NULL AND Account_Name__c!=null AND Incoterms__c!=null AND SAP_Sales_Area_Number__c!=NUll
                                                                AND SAP_Sales_Area_Number__r.SPART__c!=NULL AND SAP_Sales_Area_Number__r.VTWEG__c!=NULL AND SAP_Sales_Area_Number__r.VKORG__c!=NULL 
                                                            ];
            Map<Id, List<Sales_Area_TI__c> > mapAccountToAccountSalesArea = new Map<Id, List<Sales_Area_TI__c> > ();
            
            for(Sales_Area_TI__c accountSalesArea : listAccountSalesArea){
                List<Sales_Area_TI__c> listAccSalesArea = new List<Sales_Area_TI__c>();
                if(mapAccountToAccountSalesArea.containsKey(accountSalesArea.Account_Name__c)) listAccSalesArea = mapAccountToAccountSalesArea.get(accountSalesArea.Account_Name__c);
                listAccSalesArea.add(accountSalesArea);
                mapAccountToAccountSalesArea.put(accountSalesArea.Account_Name__c, listAccSalesArea);
            }                                              

            //System.debug('map'+mapAccountToAccountSalesArea);

            Boolean salesAreaMatched = false;
            for(Opportunity opportunity : listOpportunityWithSalesArea){
                salesAreaMatched = false;
                if(mapAccountToAccountSalesArea.containsKey(opportunity.AccountId)){
                    for(Sales_Area_TI__c accountSalesArea : mapAccountToAccountSalesArea.get(opportunity.AccountId)){
                        if(opportunity.AccountId==accountSalesArea.Account_Name__c){
                            if( opportunity.Sales_Area__c!=null && accountSalesArea.SAP_Sales_Area_Number__c!=null && opportunity.Sales_Area__c==accountSalesArea.SAP_Sales_Area_Number__c ){
                               salesAreaMatched = true; 
                            }
                            else if( (mapSalesArea.get(opportunity.Sales_Area__c)).VKORG__c!=null &&  accountSalesArea.SAP_Sales_Area_Number__r.VKORG__c!=null && (mapSalesArea.get(opportunity.Sales_Area__c)).VKORG__c == accountSalesArea.SAP_Sales_Area_Number__r.VKORG__c){
                                //if(Distri Channel left1 matches && division matches)
                                String opptySalesAreaDistriChannel = (mapSalesArea.get(opportunity.Sales_Area__c)).VTWEG__c;
                                String accountSalesAreaDistriChannel = accountSalesArea.SAP_Sales_Area_Number__r.VTWEG__c;
                                System.debug('opptySalesAreaDistriChannel '+opptySalesAreaDistriChannel+'   accountSalesAreaDistriChannel '+accountSalesAreaDistriChannel);
                                if( opptySalesAreaDistriChannel!=null &&  accountSalesAreaDistriChannel!=null && ((accountSalesAreaDistriChannel.left(2)).right(1))=='0' &&  opptySalesAreaDistriChannel.left(1)==accountSalesAreaDistriChannel.left(1)){
                                    //check division matches
                                    if( (mapSalesArea.get(opportunity.Sales_Area__c)).SPART__c == accountSalesArea.SAP_Sales_Area_Number__r.SPART__c ){
                                        salesAreaMatched = true;
                                    }
                                    else if( accountSalesArea.SAP_Sales_Area_Number__r.SPART__c=='01'){
                                        salesAreaMatched = true;
                                    }
                                }
                            }
                                                       
                            if(salesAreaMatched)
                            {
                                if(Trigger.isInsert){ opportunity.CurrencyISOCode = accountSalesArea.CurrencyISOCode; }
                                opportunity.Account_Sales_Area_TI__c = accountSalesArea.Id;
                                //opportunity.INCO_Term__c = accountSalesArea.Incoterms__c; /* Commented by Trident Team*/
                                if(!String.isBlank(accountSalesArea.Price_List__c))
                                opportunity.Price_List__c = accountSalesArea.Price_List__c;
                               
                              /* Edited by Trident Team */  
                                if(Trigger.isInsert && Trigger.isBefore && opportunity.Payment_Term__c == null && opportunity.INCO_Term__c ==null )
                                {
                                    opportunity.Payment_Term__c = accountSalesArea.Payment_Terms__c;
                                    opportunity.INCO_Term__c = accountSalesArea.Incoterms__c;
                                }
                                else if(Trigger.isUpdate && Trigger.isBefore)
                                {
                                    Opportunity tempOpty = (Opportunity)Trigger.oldMap.get(opportunity.Id);
                                    if(tempOpty.Sales_Area__c != null && tempOpty.Sales_Area__c != opportunity.Sales_Area__c && tempOpty.Payment_Term__c == opportunity.Payment_Term__c && tempOpty.INCO_Term__c == opportunity.INCO_Term__c )
                                    {
                                        opportunity.Payment_Term__c = accountSalesArea.Payment_Terms__c;
                                        opportunity.INCO_Term__c = accountSalesArea.Incoterms__c;
                                    }
                                }
                                /*Edited Ends here*/
                                //opportunity.Payment_Term__c = accountSalesArea.Payment_Terms__c;
                                opportunity.INCO_Term_Location__c = accountSalesArea.Incoterms_2__c;
                                break;
                            }
                        } // account ID match check
                            
                    }//for loop ends
                }

                if(!salesAreaMatched){ opportunity.addError('No such sales area on account');  }
            }//oppty for loop ends

        }//if set not empty
     
    }// populateInfoFromSalesArea ends

    private void setRecordTypeFromLeadConversion(){


        List<RecordType> listRecordType = [SELECT Id, DeveloperName FROM RecordType WHERE sObjectType='Opportunity'];
        Map<String, Id> mapRecordTypeNametoId = new Map<String, Id>();
        for(RecordType recordType : listRecordType){
            mapRecordTypeNametoId.put(recordType.DeveloperName, recordType.Id); 
        }

       System.debug(mapRecordTypeNametoId);

        for(Opportunity opportunity : (List<Opportunity>)Trigger.New){
            if(opportunity.Record_Type_Name_Lead__c!=null){
                System.debug('Record_Type_Name_Lead__c '+opportunity.Record_Type_Name_Lead__c);

                if( opportunity.Record_Type_Name_Lead__c.contains('International Bathrobe') &&  mapRecordTypeNametoId.containsKey('International_Bathrobe_TI')  ){ opportunity.RecordTypeId = mapRecordTypeNametoId.get('International_Bathrobe_TI'); }
                else if( opportunity.Record_Type_Name_Lead__c.contains('International Sheeting') &&  mapRecordTypeNametoId.containsKey('International_Sheeting_TI') ){ opportunity.RecordTypeId =  mapRecordTypeNametoId.get('International_Sheeting_TI') ; }
                else if( opportunity.Record_Type_Name_Lead__c.contains('International Towel') &&  mapRecordTypeNametoId.containsKey('International_Towel_TI') ){ opportunity.RecordTypeId =  mapRecordTypeNametoId.get('International_Towel_TI') ; }
                else if( opportunity.Record_Type_Name_Lead__c.contains('Domestic Bathrobe') &&  mapRecordTypeNametoId.containsKey('Domestic_Bathrobe_TI')  ){ opportunity.RecordTypeId = mapRecordTypeNametoId.get('Domestic_Bathrobe_TI'); }
                else if( opportunity.Record_Type_Name_Lead__c.contains('Domestic Sheeting') &&  mapRecordTypeNametoId.containsKey('Domestic_Sheeting_TI') ){ opportunity.RecordTypeId =  mapRecordTypeNametoId.get('Domestic_Sheeting_TI') ; }
                else if( opportunity.Record_Type_Name_Lead__c.contains('Domestic Towel') &&  mapRecordTypeNametoId.containsKey('Domestic_Towel_TI') ){ opportunity.RecordTypeId =  mapRecordTypeNametoId.get('Domestic_Towel_TI') ; }
                else if( opportunity.Record_Type_Name_Lead__c.contains('Yarn') &&  mapRecordTypeNametoId.containsKey('Yarn_TI')   ){ opportunity.RecordTypeId = mapRecordTypeNametoId.get('Yarn_TI') ; }
                else if( opportunity.Record_Type_Name_Lead__c.contains('Paper') && mapRecordTypeNametoId.containsKey('Paper_TI')  ){ opportunity.RecordTypeId =  mapRecordTypeNametoId.get('Paper_TI') ; }
                else if( opportunity.Record_Type_Name_Lead__c.contains('Chemical') && mapRecordTypeNametoId.containsKey('Chemical_TI')  ){ opportunity.RecordTypeId =  mapRecordTypeNametoId.get('Chemical_TI') ; }
            }
        }
    } //setRecordTypeFromLeadConversion ends    

    private void distributorOpptyRecordType(){

        for(Opportunity opportunity : (List<Opportunity>)Trigger.New){
            if(opportunity.Distributor_Opportunity_TI__c){
                User opptyOwner = new User(Id=opportunity.OwnerId);

                System.runAs(opptyOwner){
                    for(Schema.RecordTypeInfo recordTypeInfoObject : Schema.Opportunity.sObjectType.getDescribe().getRecordTypeInfos()) {
                        if(recordTypeInfoObject.isDefaultRecordTypeMapping() ) {
                            opportunity.RecordTypeId = recordTypeInfoObject.getRecordTypeId();
                        }
                    } 
                }
            }
        }//for loop ends
    
    }  //distributorOpptyRecordType ends

    private void setStandardPricebook(){

        Id idstandardPriceBook = '01sD0000000FXh7IAG'; //dummy value for initiation

        try{
            idstandardPriceBook = [SELECT Id FROM PriceBook2 WHERE IsStandard = true AND Unique_Key__c='StandardPricebook'][0].Id;
        }
        catch(Exception e){
            if(Test.isRunningTest()){
                idstandardPriceBook = Test.getStandardPricebookId();
            }
        }
        for(Opportunity opportunity : (List<Opportunity>)Trigger.New){
            opportunity.Pricebook2Id = idstandardPriceBook;
        }
    }//setStandardPricebook ends
}//Opportunity trigger handler class ends
 
@isTest
public class OpportunityTriggerTest {

    @testSetup
    public static void setup(){     

        TestDataFactory.createTriggerCustomSettings();
        
    }//setup ends



    public static testmethod void testUpdateTangible(){
        //create opportunity
        //create tour plan
        //create event

        Account account = ((List<Account>)TestDataFactory.createAccounts(1))[0];
        insert account;

        Opportunity opportunity = (Opportunity)SmartFactory.createSObject('Opportunity');
        opportunity.AccountId = account.Id;
        insert opportunity;

        Tour_Plan_TI__c tourPlan = (Tour_Plan_TI__c)SmartFactory.createSObject('Tour_Plan_TI__c');
        tourPlan.Status__c = 'Approved';
        tourPlan.Start_Date__c = (Date.today()).addDays(1);
        tourPlan.End_Date__c = (Date.today()).addDays(3);
        insert tourPlan;

        Event event = ((List<Event>)TestDataFactory.createPlannedEvents(1))[0];
        event.ActivityDate = (Date.today()).addDays(2);
        event.ActivityDateTime = (Date.today()).addDays(2);
        event.WhatId = tourPlan.Id;
        event.Opportunity_TI__c = opportunity.Id;
        insert event;

        //update the Opportunity
        opportunity.Amount = 112;
        update opportunity;

            
    }//testupdateTangible ends


    public static testmethod void testSetRecordTypeFromLeadConversion(){
        Account account = ((List<Account>)TestDataFactory.createAccounts(1))[0];

        insert account;

        
        List<Opportunity> listOpportunity = (List<Opportunity>)SmartFactory.createSObjectList('Opportunity',false,5);

        List<Schema.RecordTypeInfo> leadRecordTypes = Lead.getSObjectType().getDescribe().getRecordTypeInfos();

        Set<Id> setOfRecordTypeIdUsed = new Set<Id>();

        for(Opportunity opportunity : listOpportunity){

            opportunity.AccountId = account.Id;

            for (Schema.RecordTypeInfo recordType : leadRecordTypes) {
                    if (recordType.isAvailable() && recordType.isActive()) {
                        if(!setOfRecordTypeIdUsed.contains(recordType.getRecordTypeId())){ //check if same record type is used already
                            opportunity.put('Record_Type_Name_Lead__c', recordType.getName());
                            setOfRecordTypeIdUsed.add(recordType.getRecordTypeId());
                            break;
                        }                       
                    }
                }
        }

        insert listOpportunity;

    }


    public static testmethod void testDistributorOpptyRecordType(){
        
        Account account = ((List<Account>)TestDataFactory.createAccounts(1))[0];

        insert account;

        
        
        Opportunity opportunity = (Opportunity)SmartFactory.createSObject('Opportunity');
        opportunity.AccountId = account.Id;
        opportunity.Distributor_Opportunity_TI__c = true;
        //insert opportunity;


    }

    //same sales area direct match
    public static testmethod void testPopulateInfoFromSalesArea(){
        Sales_Area__c salesArea = ((List<Sales_Area__c>)TestDataFactory.createSalesAreas(1))[0];
        insert salesArea;

        Account account = ((List<Account>)TestDataFactory.createAccounts(1))[0];
        insert account;

        SmartFactory.FillAllFields = true;
        Payment_Terms__c paymentTerms = (Payment_Terms__c)SmartFactory.createSObject('Payment_Terms__c');
        insert paymentTerms;
        Sales_Area_TI__c accountSalesArea = (Sales_Area_TI__c)SmartFactory.createSObject('Sales_Area_TI__c');
        SmartFactory.FillAllFields = false;
        accountSalesArea.Account_Name__c = account.Id;
        accountSalesArea.SAP_Sales_Area_Number__c = salesArea.Id;
        accountSalesArea.Payment_Terms__c = paymentTerms.Id;
        accountSalesArea.Incoterms__c = 'CFR';
        insert accountSalesArea;

        //same sales area direct match
        Opportunity opportunity =  (Opportunity)SmartFactory.createSObject('Opportunity');
        opportunity.AccountId = account.Id;
        opportunity.Sales_Area__c= salesArea.Id;
        insert opportunity;
    }


    //different sales area fuzzy match
    public static testmethod void testPopulateInfoFromSalesArea2(){     
        Sales_Area__c salesArea1 = ((List<Sales_Area__c>)TestDataFactory.createSalesAreas(1))[0];
        salesArea1.VKORG__c = 'same';
        salesArea1.VTWEG__c='10';
        salesArea1.SPART__c='01';
        insert salesArea1;

        //division 01 match
        Sales_Area__c salesArea2 = ((List<Sales_Area__c>)TestDataFactory.createSalesAreas(1))[0];
        salesArea2.VKORG__c = 'same';
        salesArea2.VTWEG__c='12';
        salesArea2.SPART__c='23';
        insert salesArea2;

        //division exact match
        Sales_Area__c salesArea3 = ((List<Sales_Area__c>)TestDataFactory.createSalesAreas(1))[0];
        salesArea3.VKORG__c = 'same';
        salesArea3.VTWEG__c='12';
        salesArea3.SPART__c='01';
        insert salesArea3;



        Account account = ((List<Account>)TestDataFactory.createAccounts(1))[0];
        insert account;

        SmartFactory.FillAllFields = true;
        Payment_Terms__c paymentTerms = (Payment_Terms__c)SmartFactory.createSObject('Payment_Terms__c');
        insert paymentTerms;
        Sales_Area_TI__c accountSalesArea = (Sales_Area_TI__c)SmartFactory.createSObject('Sales_Area_TI__c');
        SmartFactory.FillAllFields = false;
        accountSalesArea.Account_Name__c = account.Id;
        accountSalesArea.SAP_Sales_Area_Number__c = salesArea1.Id;
        accountSalesArea.Payment_Terms__c = paymentTerms.Id;

        insert accountSalesArea;

        Opportunity opportunity =  (Opportunity)SmartFactory.createSObject('Opportunity');
        opportunity.AccountId = account.Id;
        opportunity.Sales_Area__c= salesArea2.Id;
        insert opportunity;


        Opportunity opportunity2 =  (Opportunity)SmartFactory.createSObject('Opportunity');
        opportunity2.AccountId = account.Id;
        opportunity2.Sales_Area__c= salesArea3.Id;
        insert opportunity2;



    }

    public static testmethod void testStampPlant(){

        

        String productCode1 = 'A1';


        //Product
        Product2 product = new Product2(Name='TestProduct 1', SAP_Product_Code__c = productCode1, isActive=true);
        insert product;

        PriceBookEntry pbeStandard = new PriceBookEntry(
            Product2Id = product.Id, Pricebook2Id = Test.getStandardPricebookId(), UnitPrice = 10, CurrencyISOCode ='INR', isActive=true);
        insert pbeStandard;

       
       
        Sales_Area__c salesArea = ((List<Sales_Area__c>)TestDataFactory.createSalesAreas(1))[0];
        insert salesArea;

        //add plant on oppty
        Plant__c plant = (Plant__c)SmartFactory.createSObject('Plant__c');
        insert plant;

         //create Product Sales Area
        Product_Sales_Area__c productSalesArea = new Product_Sales_Area__c(
            Material_Code__c = product.Id, Sales_Area__c = salesArea.Id);
        insert productSalesArea;


        Account account = ((List<Account>)TestDataFactory.createAccounts(1))[0];
        account.CurrencyISOCode = 'INR';
        insert account;

        SmartFactory.FillAllFields = true;
        Payment_Terms__c paymentTerms = (Payment_Terms__c)SmartFactory.createSObject('Payment_Terms__c');
        insert paymentTerms;
        Sales_Area_TI__c accountSalesArea = (Sales_Area_TI__c)SmartFactory.createSObject('Sales_Area_TI__c');
        SmartFactory.FillAllFields = false;
        accountSalesArea.Account_Name__c = account.Id;
        accountSalesArea.SAP_Sales_Area_Number__c = salesArea.Id;
        accountSalesArea.Payment_Terms__c = paymentTerms.Id;
        accountSalesArea.CurrencyISOCode ='INR';
        insert accountSalesArea;

        //same sales area direct match
        Opportunity opportunity =  (Opportunity)SmartFactory.createSObject('Opportunity');
        //set yarn recordtype
        opportunity.Business_Division__c='Yarn';
        opportunity.AccountId = account.Id;
        opportunity.Sales_Area__c= salesArea.Id;
        opportunity.CurrencyISOCode ='INR';
        insert opportunity;


        //positiveTest
        OpportunityLineItem oli = new OpportunityLineItem(
            Product_Code__c= productCode1, OpportunityId=opportunity.Id, Quantity=5);

        insert oli;
        try{
            opportunity.Plant__c = plant.Id;
            update opportunity;
        }catch(Exception e){}
       

    }   


}

 
Best Answer chosen by Akash Garg 2
Akash Garg 2Akash Garg 2
Hi Anas,
Thanks a lot for help.
I have figured it out. Just Disable the Lookup Filter criteria and then deploy the Class won't give that error.

Regards,
Akash Garg

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Akash,

Greetings to you!

The issue is because of the lookup filter. This error occurs when there is a Lookup Field filter defined on an Object and you modify it so that the update doesn't reflect the filter criteria. 

Resolve the Error:
If you could identify what is the lookup criteria and what value you are inserting in code then you can resolve the problem.  

Check to see if any filters are defined on the Object and make sure any modifications are adhering to the Filter Criteria.

You can check if there are any filters on the Object by following these steps for the Classic UI:
 
  • Go to Setup | Customize | <Object>| Fields. 
  • Scroll through your Standard and Custom Fields until you find a Lookup Field. 
  • Click on the Field Label and review the detail page to see if any filters exist. 
  • Review the Filter Criteria to be sure your modifications adhere to it. 

For Lightning, you can check with the following:
 
  • Go to Setup | Object Manager | <Object>| Fields & Relationship. 
  • Scroll through your Standard and Custom Fields until you find a Lookup Field. 
  • Click on the Field Label and review the detail page to see if any filters exist. 
  • Review the Filter Criteria to be sure your modifications adhere to it. 

Reference: Knowledge Article: https://help.salesforce.com/articleView?id=000002872&language=en_US&type=1

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Akash Garg 2Akash Garg 2
Hi Anas,

Thanks for the quick Reply.

Filter is filed SAP_Sales_Area_Number__c of object Sales_Area_TI__c which is as follow : - 
SAP Sales Area Number: SPART EQUALS 01

Kindly help in correctly the test class.

Regards,
Akash Garg
Akash Garg 2Akash Garg 2
Hi Anas,
Thanks a lot for help.
I have figured it out. Just Disable the Lookup Filter criteria and then deploy the Class won't give that error.

Regards,
Akash Garg
This was selected as the best answer