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
Ghulam Murtaza 5Ghulam Murtaza 5 

need help in Creating Test Data for Apex Tests

hello,

i am a newbie to salesforce and trying to complete this trailhead challenge and unable to find a way through apex to generate this method for creating new contacts with unique id. as one requirement to pass the challenge is "The 'generateRandomContacts' method must be capable of consistently generating contacts with unique first names."

If somebody successfully completed the task kindly help me.

regards,
Best Answer chosen by Ghulam Murtaza 5
Ghulam Murtaza 5Ghulam Murtaza 5
hi pankaj,
i have completed the task somehow. my friend completed it with a simple code i.e. 
public class RandomContactFactory{
   public static List<Contact> generateRandomContacts(integer n,string lastname){
       integer n1= n;
       list<contact> c=[select  FirstName from contact limit : n1];
       return c;
   }
   
}


but for me it was giving error of class not created as static or either the method is not returning the first name. so for me it worked as follows:

public class RandomContactFactory{

    public static List<Contact> generateRandomContacts(integer n,string LastName){
    integer n1=n;
    List<contact> c1 = new list<contact>();
    list<contact> c2 =new list<contact>();
     c1 = [select FirstName from Contact Limit : n1];
     integer i=0;
     for(contact cnew : c1){
     contact cnew1 = new contact();
     cnew1.firstname = cnew.firstname + i;
     
     c2.add(cnew1);
     i++;
     }
    return c2;
    
    }
}

All Answers

Pankaj_GanwaniPankaj_Ganwani
Hi,

In test class, you can do make use of for loop:

for(Integer i = 0 ; i< 200;i++)
{
    lstContact.add(FirstName = 'Test'+i, LastName = 'Contact');
}
insert lstContact;
Ghulam Murtaza 5Ghulam Murtaza 5
hey pankaj,


thanks for the quick response. Can't i do this in any other class than the test class. as the challenge asks not to use test class. and the class should return the list of contacts with incoming parameters something like this.

public static List<Contact> generateRandomContacts(Integer CNumber,string PostalCode)

how do i use the loop for both the parameters?


Thanks in advance.
Pankaj_GanwaniPankaj_Ganwani
Hi,
 
public static List<Contact> generateRandomContacts(Integer CNumber,string PostalCode)
{
List<Contact> lstContact = new List<Contact>();
for(Integer i = 0 ; i< CNumber;i++)
{
    lstContact.add(FirstName = 'Test'+i, LastName = 'Contact', OtherPostalCode = PostalCode);
}
insert lstContact;
return lstContact;
}

 
Ghulam Murtaza 5Ghulam Murtaza 5

hey pankaj,

i was doing the same thing and was confused on how to get it right...because ..1) The challenge asks not to insert the contact into salesforce database. 2) the challenge asks for Apex class that returns a list of contacts based on two incoming parameters: one for the number of contacts to generate, and the other for the last name. and at the same time the problem i asked in my question in the start that class must be able to genrate first name with unique names consistently. so the first name variable is should be declared as a string type first or what ? because in the code above its going to be an error because FirstName is nor declared anywhere and i can't make a parameter in the method as wel.


sorry for the long text. it has got me confused. 

regards,

Pankaj_GanwaniPankaj_Ganwani
Hi,

Please remove the DML statement and otherpostalcode field then. and assign the postal code value to LastName field. As you can see, the FirstName will be having the unique names as we are appending the integer number at the end of the 'Test'. Can you please share the screenshot of the error what you are getting at the time of verifying?
Ghulam Murtaza 5Ghulam Murtaza 5
hi pankaj,
i have completed the task somehow. my friend completed it with a simple code i.e. 
public class RandomContactFactory{
   public static List<Contact> generateRandomContacts(integer n,string lastname){
       integer n1= n;
       list<contact> c=[select  FirstName from contact limit : n1];
       return c;
   }
   
}


but for me it was giving error of class not created as static or either the method is not returning the first name. so for me it worked as follows:

public class RandomContactFactory{

    public static List<Contact> generateRandomContacts(integer n,string LastName){
    integer n1=n;
    List<contact> c1 = new list<contact>();
    list<contact> c2 =new list<contact>();
     c1 = [select FirstName from Contact Limit : n1];
     integer i=0;
     for(contact cnew : c1){
     contact cnew1 = new contact();
     cnew1.firstname = cnew.firstname + i;
     
     c2.add(cnew1);
     i++;
     }
    return c2;
    
    }
}
This was selected as the best answer
Raghu.2020Raghu.2020
Hi Ghulam,

You can check out my below code. Hope this helps.

public class RandomContactFactory {
    public static list<contact> generateRandomContacts(integer n, string m) {
        list<contact> con = new list<contact>();
        for(integer i=1; i<n+1; i++) {   
            contact c = new contact(firstname='test'+i,lastname=m);
            con.add(c);
        }
        return con;
    }
}
leemeisterleemeister
Hello,

There's a similar challenge on the Developer Beginner trailhead.
 
public static Contact[] generateRandomContacts(Integer numOfContacts, String lastName){
		Contact[] existing = [SELECT FirstName, LastName FROM Contact WHERE LastName =: lastName LIMIT : numOfContacts];
		Contact[] generated = new Contact[]{};
	
		for(Integer o = 0; o < numOfContacts; o++){
				generated.add(new Contact(FirstName = 'Test ' + o));
		}
		return generated;
	}

 
Sangram Kesari RaySangram Kesari Ray
This worked for me.
 
public class RandomContactFactory {
    public static List<Contact> generateRandomContacts(Integer count, String name) {
        List<Contact> contactList = new List<Contact>();
        
        for(Integer index = 1; index <= count; index++) {
            Contact c = new Contact();
            c.FirstName = name + index;
            contactList.add(c);
        }
        
        return contactList;
    }
}

 
Kishan MalepuKishan Malepu
Hi,
 You can try this...Its wotking for me
public class RandomContactFactory {
    public static List<Contact> generateRandomContacts(Integer noofcontacts, String LName){
        List<Contact> cons = new List<Contact> ();
        for(Integer i=0; i< noofcontacts; i++ ){
            cons.add(new Contact (FirstName = 'Test' + i,LastName = Lname));
             }
       // system.debug(cons);
       return cons;
     }
}
You can execute from anonymous window as : RandomContactFactory.generateRandomContacts(2,'Pencil');
Mario Alberts 3Mario Alberts 3
Thanks Kishan! 

I completed the challenge!

M
James Wenham 12James Wenham 12
This worked for me

public class RandomContactFactory {
    public static List<Contact> generateRandomContacts(Integer numcts, String lastn){
        List<Contact> cts = new List<Contact>();
        
        for(Integer i=0;i<numcts;i++){
        Contact c = new Contact(Firstname='Test'+ i);
            cts.add(c);
            }
        return cts;
    
     }
        
}
Amjad Khan 66Amjad Khan 66
This is working fine..
public class RandomContactFactory {
    public static List<Contact> generateRandomContacts(Integer count, String name) {
        List<Contact> contactList = new List<Contact>();
        
        for(Integer index = 1; index <= count; index++) {
            Contact c = new Contact();
            c.FirstName = name + index;
            contactList.add(c);
        }
        
        return contactList;
    }
}
pirouz sourati zanjanipirouz sourati zanjani
this is a workig solution ..
public class RandomContactFactory {
    public static List<Contact> generateRandomContacts (Integer numOfCon, String ConLastName){
        List<Contact> conList = new List<Contact>();
        for(Integer i=1; i<numOfCon;i++){
            conList.add(new Contact(FirstName='Test ' + i, LastName = ConLastName));
        }
        return conlist;
    }
}

 
Aviroop Chowdhury 2Aviroop Chowdhury 2
@Pirouz : Your solution needs a bit of tweak else it ll fail. i should count from 0 or should be equal or less or equal to numofCon. Also ConLastName is a parameter reference. Check this :

 public class RandomContactFactory {
    public static List<Contact> generateRandomContacts (Integer numOfCon, String ConLastName){
        List<Contact> conList = new List<Contact>();
        for(Integer i=0; i<numOfCon;i++){
            conList.add(new Contact(FirstName='Test ' + i, LastName= string.valueof(ConLastName)));
                   }
        system.debug(conlist);
        return conlist;
    }
}
Kamran HanifKamran Hanif
Many people answered this question, I´m going to leave this code here I hope it gives a clear view.

public class RandomContactFactory 
{
    public static list<contact> generateRandomContacts(integer numofContacts, string LName) 
    {
        //this is a list which will hold contacts generated
        List<Contact> ListtoReturn = new List<Contact>();

        for(integer i=0; i<numofContacts; i++) {   
            Contact con = new contact(FirstName='Test'+i , LastName=LName);
            ListtoReturn.add(con);
        }
        return ListtoReturn;
    }
}
UK KiltsUK Kilts
Heavy Denim Kilt (https://www.ukkilt.com/product-category/mens-kilts/denim-kilts/)Durable Fabric Tactical Pocket Comfortable & Stylish The Denim Kilt With Tactical Pocket . It is made by using a high quality durable denim.
Help DiskHelp Disk
If you find Free Latest movies download website,  
Then i invite you to the Todaypk  (https://www.todaypkmovies.in" target="_self)
 website for free latest movies download
tony stark 80tony stark 80
 public class RandomContactFactory {
    public static List<Contact> generateRandomContacts (Integer numOfCon, String ConLastName){
        List<Contact> conList = new List<Contact>();
        for(Integer i=0; i<numOfCon;i++){
            conList.add(new Contact(FirstName='Test ' + i, LastName= string.valueof(ConLastName)));
                   }
        system.debug(conlist);
https://techandskill.com/
paul smith 66paul smith 66
watch online hd dubbed movies for free at https://bollywoodmastian.com/ipagal/
Abhishek DalviAbhishek Dalvi
public class RandomContactFactory {
    public static List<Contact> generateRandomContacts(Integer ConNum, String LName){
        List<Contact> Cons = new List<Contact>();
        
        for(integer i=0; i<=ConNum; i++){
            Contact C = new Contact(FirstName='TestContact'+i , LastName=LName);
            Cons.add(c);
        }
        Return Cons;
    }
}
Siddhi SalvekarSiddhi Salvekar
public class RandomContactFactory {
    public static List<Contact> generateRandomContacts(integer numOfContacts, string inputLastName){
        List<Contact> listOfContacts = new List<Contact>();
        for(integer i=1;i<=numOfContacts;i++){
            listOfContacts.add(new Contact(FirstName='Test '+i,
                                       LastName=inputLastName));
        }
        return listOfContacts;
    }
}

 
Mayank ParnamiMayank Parnami
This worked for me.

public class RandomContactFactory{

public static List<Contact> generateRandomContacts(integer digit, string lastNameInput){
List<Contact> contactList = new List<Contact>();
for (integer i=0;i<digit;i++){
contactList.add(new Contact(LastName =lastNameInput, FirstName = 'Test'+ i));
}
return contactList;
}
}
voleti venkateshvoleti venkatesh

public class RandomContactFactory {
    public static List<Contact> generateRandomContacts(Integer numcon  , String lastname){
        List<Contact> conList = new List<Contact>();
        for(Integer i=0;i<numcon;i++){
            conList.add(New Contact(FirstName='Test '+i,LastName=lastname));
        }
        return conList;
    }

}
umair khan 15umair khan 15
public class RandomContactFactory {
    public static List<contact> generateRandomContacts(Integer noOfRecords, String lastName){
     List<contact> contactList= new List<Contact>();
        for(integer i=0; i<noOfRecords; i++){
         Contact con = new Contact(LastName =lastName,FirstName =''+i);
         contactList.add(con);

        }



    return contactList;
    }
}

I Completed By Executing the Above Code
vb patelvb patel
welcome back friends. today below on our website and in this article we are going to talk about the my as you all are waiting for the


https://surveyguide.onl/
Praneeth YanamadalaPraneeth Yanamadala
Why shouldn't we write @isTest before the class like in the example shown in the Trialhead for 'TestDataFactory' class.
Lalithashree G 3Lalithashree G 3
@Praneeth Yanamadala
Hey Praneeth,

The challenge itself asks us to create an Apex class but not the test class:
"Create an Apex class that returns a list of contacts based on two incoming parameters: the number of contacts to generate and the last name. Do not insert these contact records into the database."

You can however create a test class for this to test your code coverage. I'm attaching a sample test code, which does cover 100% of the code :D
But this code doesn't cover other scenarios like boundary values, negative values, invalid inputs.
 
@isTest
public class testRandomContactFactory {
    @isTest
    public static List<Contact> testgenerateRandomContacts(){
        List<Contact> cont = new List<Contact>();
        RandomContactFactory.generateRandomContacts(5, 'MyLastName');
        return cont;
    }

}

 
cracker barrelcracker barrel
I thougt the wordpress is best platform for the same. you should check the site like https://icrackerbarrel-survey.com/ and one more thing that you should check is www crackerbarrel survey com win a rocker (https://icrackerbarrel-survey.com/)
Canvas FISDCanvas FISD

Canvas FISD Login Guide at fisd.instructure.com – 2022 (https://topsurvey.onl/canvas-fisd-login/" target="_blank)
Rixyuer yuer 5Rixyuer yuer 5
Burger King Customer Experience Survey. So the company can make a change in their system format to reduce the issue of the customer so the customer can enjoy Burger King’s service.  (https://surveydetails.com/burger-king-survey-www-mybkexperience-com/)
doxesop marrydoxesop marry

In your blog I was happy to see your article, better than last time, and have made great progress, I am very pleased. I am looking forward to your article will become better and better. Cheesecake Factory Happy Hour
fdgr tetryfdgr tetry
If you’re a frequent customer of Mary Brown’s Chicken and Taters, then you’re eligible to be a winner of free Mary Brown’s Coupons through TellMary.SMG survey.
jems bondjems bond
Truliant Federal Credit employee login 
hello friends,
Truliant Federal Credit Union Login – Here in this article, you will get to learn about how to login into the Truliant Federal Credit Union Login portal.
So please read this article, at last, and learn about the Truliant  Federal Credit Union at www.truliantfcu.com and various other proceedings.
Let’s get started…
http://logina2z.com/truliant-federal-credit-union-login/
harry Davisharry Davis
Truliant Federal Credit employee login 
hello friends,
Truliant Federal Credit Union Login – Here in this article, you will get to learn about how to login into the Truliant Federal Credit Union Login portal.
So please read this article, at last, and learn about the Truliant  Federal Credit Union at www.truliantfcu.com and various other proceedings.
Let’s get started…
https://salonpricelist.com/onewalmart-walmartone/
weweyot marryweweyot marry

KFC Menu With Prices (https://kfcsecretmenu.info/kfc-menu-with-prices/) – KFC (Kentucky Fried Chicken) is a fast-food restaurant chain specializing in fried chicken.
jems bondjems bond
 My Estub employee login 
hello friends,
My Estub Login – Here in this article, you will get to learn about how to login into the My Estub Login portal.
So please read this article, at last, and learn about the My Estub Login and various other proceedings.
Let’s get started…
http://logina2z.com/my-estub-login/
jems bondjems bond
The US Assure employee login 
hello friends,
Us Assure Agent Login Portal – Here in this article, you will get to learn about how to login into the Us Assure Agent Login Portal.
So please read this article, last, and learn about the Us Assure Agent Login and various other proceedings.
Let’s get started…  
http://logina2z.com/us-assure-agent-login/
jems bondjems bond
Revoobit Login – Here in this article, you will get to learn about how to login into the Revoobit Login Portal.
So please read this article, at last, and learn about the Revoobit Login Portal  and various other proceedings.
Let’s get started…
http://logina2z.com/how-to-revoobit-login-portal/
jems bondjems bond
ALDI Shopping Login – Here in this article, you will get to learn about how to login into the ALDI Shopping Login portal.
So please read this article, at last, and learn about the ALDI Shopping Login and various other proceedings.
Let’s get started...
http://logina2z.com/aldi-shopping-login/