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
srinu namani 12srinu namani 12 

How can I pass values to master detail field in a test class.

I am trying to pass values to a master detail field in my Test Class. I tried to pass values as I do for normal fields, but it is throwing Error.

Can any one suggest me how can i do this
James LoghryJames Loghry
You should create both the master and the child records in your test class.  The master record you'll create first, and then the children records go afterward.  Note, it's the same process for specifying lookup fields.  Here's a simple Account / Contact example:
 
static testmethod void testMasterDetail(){
    List<Account> accounts = new List<Account>{
        new Account(
            Name = 'MyTestAccount'
        )
    };
    insert accounts;

    List<Contact> contacts = new List<Contact>{
        new Contact(AccountId=accounts.get(0).Id,Lastname='Contact1')
        new Contact(AccountId=accounts.get(0).Id,Lastname='Contact2')
        new Contact(AccountId=accounts.get(0).Id,Lastname='Contact3')
    };
    insert contacts;

    Test.startTest();
    //call your apex to test here
    Test.stopTest();

    System.assertEquals(expectedResult,actualResult);
}

 
varun_vatsavarun_vatsa
Its just you need to pass the "id" value of your master object record. So for example if you are trying to attach one Contact to an Account.

Account acc = new Account();
acc.LastName = "Test Acc";
insert acc;

Contact con = new Contact();
con.lastName = "Con Last Name";
con.Account = acc.id;
insert con;
srinu namani 12srinu namani 12
Here is my Class

public class OverrideNewButtonComponentController {
    Public string sObjectType {get; set;}
    Public string keyPrefix {get; set;}
    Public string infoProLabel {get; set;}
    Public string infoProLawonLabel {get; set;}
    
    List<Line_of_Business__c > listInfoProLawson = new List<Line_of_Business__c >();
    public OverrideNewButtonComponentController(String sobjectName, String objPrefix) {
        sObjectType=sobjectName;
        keyPrefix=objPrefix;
    }
    public OverrideNewButtonComponentController(){}

    public PageReference init() {
    
          if (ApexPages.currentPage().getParameters().get('RecordType') == null) {
          Schema.DescribeSObjectResult describeLead = Schema.SObjectType.Lead;
          List<Schema.RecordTypeInfo> rtInfos = describeLead.getRecordTypeInfos();
          for(Schema.RecordTypeInfo rtInfo : rtInfos) {
            if(rtInfo.getName() != 'Master' && rtInfo.isAvailable()) {
            ApexPages.currentPage().getParameters().put('RecordType', rtInfo.getRecordTypeId());
           }
          }
          
         }
         
        String userLawson = String.Valueof([Select id, Lawson_Division__c from User where id = : Userinfo.getUSerId()].Lawson_Division__c);
        String accid='';
        if(ApexPages.currentPage().getParameters().get('accid') != null){
            accid = ApexPages.currentPage().getParameters().get('accid');
        }
        if (userLawson != null) {
            listInfoProLawson = [SELECT Id, Name, Lawson_Division__c, Infopro_Division__r.Name from Line_of_Business__c where Lawson_Division__r.Name = :userLawson];
            system.debug('sObjectType==' + sObjectType);
            if (listInfoProLawson.size() >= 1 && listInfoProLawson.get(0).Name != null && listInfoProLawson.get(0).Infopro_Division__r.Name != null) {
                String labelVal ;
                if(sObjectType=='Opportunity')
                    labelVal = System.Label.OpportunityNewButtonOverRideLabel;
                else if(sObjectType=='Lead')
                    labelVal= System.Label.LeadNewButtonOverRideLabel;
                labelVal = labelVal.trim();
                List<String> labels = labelVal.split(',');
                System.debug('labels==' + labels);
                infoProLawonLabel = labels.get(0).trim();
                infoProLabel = labels.get(1).trim();
                System.debug(sObjectType+'sObjectTypes---');
                
                //return new PageReference('/setup/ui/recordtypeselect.jsp?ent=' + sObjectType + '&nooverride=1&retURL=%2F'+keyPrefix+'%2Fo&save_new_url=%2F'+keyPrefix+'%2Fe%3FretURL%3D%252F'+keyPrefix+'%252Fo&' + infoProLawonLabel + '=' + listInfoProLawson.get(0).Name + '&' + infoProLawonLabel + '_lkid=' + listInfoProLawson.get(0).Id + '&' + infoProLabel + '=' + listInfoProLawson.get(0).Infopro_Division__r.Name);
                if(sObjectType=='Lead' && (ApexPages.currentPage().getParameters().get('RecordType') == Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Field Sales Lead').getRecordTypeId() || ApexPages.currentPage().getParameters().get('RecordType') == Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Refer Republic Lead').getRecordTypeId())){
                    Pagereference page = new PageReference('/'+keyPrefix+'/e?nooverride=1&retURL=%2F'+keyPrefix+'%2Fo&save_new_url=%2F'+keyPrefix+'%2Fe%3FretURL%3D%252F'+keyPrefix+'%252Fo&' + infoProLawonLabel + '=' + listInfoProLawson.get(0).Name + '&' + infoProLawonLabel + '_lkid=' + listInfoProLawson.get(0).Id + '&' + infoProLabel + '=' + listInfoProLawson.get(0).Infopro_Division__r.Name + '&lea16country=USA&RecordType='+ApexPages.currentPage().getParameters().get('RecordType'));
                    //page.setRedirect(true);
                    return page;
                }
                else if(sObjectType=='Opportunity' && (ApexPages.currentPage().getParameters().get('RecordType') == Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Field Sales Opportunity').getRecordTypeId())){
                System.debug(sObjectType+'inside sObjectTypes---');
                    Pagereference page = new PageReference('/'+keyPrefix+'/e?nooverride=1&retURL=%2F'+keyPrefix+'%2Fo&save_new_url=%2F'+keyPrefix+'%2Fe%3FretURL%3D%252F'+keyPrefix+'%252Fo&' + infoProLawonLabel + '=' + listInfoProLawson.get(0).Name + '&' + infoProLawonLabel + '_lkid=' + listInfoProLawson.get(0).Id + '&' + infoProLabel + '=' + listInfoProLawson.get(0).Infopro_Division__r.Name+'&accid='+accid+'&RecordType='+ApexPages.currentPage().getParameters().get('RecordType'));
                    //page.setRedirect(true);
                    return page;
                }
                return new PageReference('/'+keyPrefix+'/e?nooverride=1&retURL=%2F'+keyPrefix+'%2Fo&save_new_url=%2F'+keyPrefix+'%2Fe%3FretURL%3D%252F'+keyPrefix+'%252Fo&' + infoProLawonLabel + '=' + listInfoProLawson.get(0).Name + '&' + infoProLawonLabel + '_lkid=' + listInfoProLawson.get(0).Id + '&' + infoProLabel + '=' + listInfoProLawson.get(0).Infopro_Division__r.Name+'&accid='+accid);
            }
        } 
        
            //return new PageReference('/setup/ui/recordtypeselect.jsp?ent=' + sObjectType + '&nooverride=1&retURL=%2F'+keyPrefix+'%2Fo&save_new_url=%2F'+keyPrefix+'%2Fe%3FretURL%3D%252F'+keyPrefix+'%252Fo');
        if(sObjectType=='Lead' && (ApexPages.currentPage().getParameters().get('RecordType') == Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Field Sales Lead').getRecordTypeId() || ApexPages.currentPage().getParameters().get('RecordType') == Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Refer Republic Lead').getRecordTypeId())){
            return new PageReference('/'+keyPrefix+'/e?nooverride=1&retURL=%2F'+keyPrefix+'%2Fo&save_new_url=%2F'+keyPrefix+'%2Fe%3FretURL%3D%252F'+keyPrefix+'%252Fo&lea16country=USA&RecordType='+ApexPages.currentPage().getParameters().get('RecordType'));
        }
        else if(sObjectType=='Opportunity' && (ApexPages.currentPage().getParameters().get('RecordType') == Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Field Sales Opportunity').getRecordTypeId())){
            return new PageReference('/'+keyPrefix+'/e?nooverride=1&retURL=%2F'+keyPrefix+'%2Fo&save_new_url=%2F'+keyPrefix+'%2Fe%3FretURL%3D%252F'+keyPrefix+'%252Fo&RecordType='+ApexPages.currentPage().getParameters().get('RecordType')+'&accid='+accid);
        }
        else if(sObjectType=='Lead' && (ApexPages.currentPage().getParameters().get('RecordType') == Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Special Waste Leads').getRecordTypeId())){
           return new PageReference('/apex/SPWLead?ent=Lead&RecordType='+ApexPages.currentPage().getParameters().get('RecordType')+'&retURL=SPWLead&save_new_url=00Q/e');
        }     
        return new PageReference('/'+keyPrefix+'/e?nooverride=1&retURL=%2F'+keyPrefix+'%2Fo&save_new_url=%2F'+keyPrefix+'%2Fe%3FretURL%3D%252F'+keyPrefix+'&accid='+accid);
    }

}





my Test Class

@istest
private class TestOverrideNewButtonComponentController {

Static testmethod void OverrideNewButtonComponentController() {
OverrideNewButtonComponentController ride = new OverrideNewButtonComponentController(); 
ride.init();

List<Line_of_Business__c > lst = new List<Line_of_Business__c >();

Line_of_Business__c  lb1=new Line_of_Business__c();
Lawson_Division__c   ld1 = new Lawson_Division__c();
Infopro_Division__c  id1 = new Infopro_Division__c();

Profile p = [SELECT Id FROM Profile WHERE Name='field sales'];
User u = new User(Alias = 'standt1', Email='standarduser1@testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='myorg1@testorg.com');

System.runAs(u) {

ld1.name = 'test';
insert ld1;
id1.name = 'testinfo';
insert id1;
lb1.name = 'testLawson';
//lb1.Infopro_Division__c = 'testinfo1';
//lb1.Lawson_Division__c = 'test1';
//insert lb1;


}

}

//user U = new user ( 
}

 
srinu namani 12srinu namani 12
Line of Business is the junction object
Lawson Division is having master detail relation with Line of Business
Infopro Division is having master detail relation with Line of Business
 
varun_vatsavarun_vatsa
Have you tried this in your code?

lb1.Infopro_Division__c = id1;
lb1.Lawson_Division__c = ld1;