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
Satyanarayana PusuluriSatyanarayana Pusuluri 

Stuck on Trailhead Challenge for Creating Test Data for Apex Tests

Create an 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. The list should NOT be inserted into the system, only returned. The first name should be dynamically generated and should be unique for each contact record in the list.The Apex class must be called 'RandomContactFactory' and be in the public scope.
The Apex class should NOT use the @isTest annotation.
The Apex class must have a public static method called 'generateRandomContacts' (without the @testMethod annotation).
The 'generateRandomContacts' method must accept an integer as the first parameter, and a string as the second. The first parameter controls the number of contacts being generated, the second is the last name of the contacts generated.
The 'generateRandomContacts' method should have a return type of List<Contact>.
The 'generateRandomContacts' method must be capable of consistently generating contacts with unique first names.
For example, the 'generateRandomContacts' might return first names based on iterated number (i.e. 'Test 1','Test 2').
The 'generateRandomContacts' method should not insert the contact records into the database.

I create a class as bellow

public class RandomContactFactory{
   public static List<Contact> generateRandomContacts(integer n,string lastnames){

       list<contact> c= [select  FirstName from contact where LastName =: lastnames limit : n ];
       
       return c;
   }
   
}

but i'm getting error as below

Challenge not yet complete... here's what's wrong: 
Executing the 'generateRandomContacts' method failed. Either the method does not exist, is not static, or did not return the correct set of Contact records.

Please let me know where the issue?
Best Answer chosen by Satyanarayana Pusuluri
Neetu_BansalNeetu_Bansal
Hi,

Use this code as I was able to complete the challenge.
public with sharing class RandomContactFactory
{
	public static List<Contact> generateRandomContacts( Integer noOfContacts, String lastName )
	{
		List<Contact> contacts = new List<Contact>();
		
		for( Integer i = 0; i < noOfContacts; i++ )
		{
			Contact con = new Contact( FirstName = 'Test '+i, LastName = lastName );
			contacts.add( con );
		}
		
		return contacts;
	}
}

Let me know, if you need any other help. If this post helps, please mark it as best answer.

Thanks,
Neetu

All Answers

Neetu_BansalNeetu_Bansal
Hi,

Use this code as I was able to complete the challenge.
public with sharing class RandomContactFactory
{
	public static List<Contact> generateRandomContacts( Integer noOfContacts, String lastName )
	{
		List<Contact> contacts = new List<Contact>();
		
		for( Integer i = 0; i < noOfContacts; i++ )
		{
			Contact con = new Contact( FirstName = 'Test '+i, LastName = lastName );
			contacts.add( con );
		}
		
		return contacts;
	}
}

Let me know, if you need any other help. If this post helps, please mark it as best answer.

Thanks,
Neetu
This was selected as the best answer
Satyanarayana PusuluriSatyanarayana Pusuluri
Thanks Neetu

I completed the Challenge :-)

Satya P
SUCHARITA MONDALSUCHARITA MONDAL

Hi Neetu,

 

Why "With Sharing" is used in (public with sharing class RandomContactFactory)

What with Sharing is doing here???
 

Neetu_BansalNeetu_Bansal
Hi Sucharita,

It is good practice to use with sharing, as it will impose all your sharing rules created. It will help in preventing yor data to be accessed by users that don't have the permissions.

Thanks,
Neetu
pravin joshipravin joshi
thanks, Neetu code work properly
pravin joshipravin joshi
Hi I am new in sfdc.... I have read about with sharing and without sharing but still little bit confuse between them..... plz can anybody tell in easy way........
Thanx.................
Praveen ShankarPraveen Shankar
public class RandomContactFactory {
    public static list<contact> generateRandomContacts(integer CON , string LN){
       list<contact> CON1 = new list<contact>();
       for (integer i=0 ;i<CON ; i++){
           contact C = new contact(firstname = 'test' + i , lastname= LN);
           CON1.add(C);
       }
        return CON1 ;
   }
  //  return CON1 ;
}
vijay kumar rekulvijay kumar rekul
Hi,
public class RandomContactFactory {
 
        public static List<Contact> generateRandomContacts(Integer numberofcontacts, string l_name){
            
            List<Contact> cnts = new List<Contact>();
            for(integer i=0; i<numberofcontacts; i++){
                contact cnts1=New contact();
                string Name='Test'+i;                
                    cnts1.FirstName=Name;//add the content of name variable to First Name field of contact object
                cnts1.LastName=l_name;//add the content of name variable to LastName field of contact object
                cnts.Add(cnts1);//add to the list collection, Contact                                  
            }
            return cnts;//returning the list to the called method 
        }
}
Shubham MaskeShubham Maske
My answer  and it worked :
public class RandomContactFactory {
    public static List <Contact> generateRandomContacts(Integer numCont, String conLstName) {
        List<Contact> listContact = new List<Contact>();
        
        for (Integer i=0; i < numCont; i++ ){
            Contact con = new Contact(FirstName='Test' +i,LastName='conLstName');
            listContact.add(con);
        }
        return listContact;
	}
}

 
Richard Fosu 12Richard Fosu 12
Hi Shubham,

I've used your code to pass the challenge but in comparison to my code(below), I can see you've written the LastName value as a String; 'conLstName', not variable reference.

Despite this, your code works which defeats the purpose of passing the LastName parameter in the first place. Have I misunderstood the syntax of referencing a string variable?

my code:
public with sharing class RandomContactFactory {   
    public static List<Contact> generateRandomContacts (Integer iterationSize, String lastName){        
       Contact[] contacts;
        
       for(Integer i=0 ; i < iterationSize ; i++){            
          Contact newContact = new Contact (FirstName = 'Test '+i, LastName = lastName);       
          contacts.add(newContact); 
        }        
        return contacts;
    }
}
Abhishek DalviAbhishek Dalvi
I came up with below code and it worked fine for me.

public with sharing 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;
    }
}
ani ghoani gho
public class RandomContactFactory{
	public static List<Contact> generateRandomContacts( Integer maxNumberOfContacts, String lName ){
        
      
        List<Contact> contacts = new List<Contact>();        
		Integer counter=1;
        
		while(counter<=maxNumberOfContacts){
            Contact con = new Contact(LastName = lName );
			con.FirstName=('Test '+counter);
			contacts.add(con);
            counter++;
		}		
		return contacts;
	}
}


 
Javed Iqbal 15Javed Iqbal 15
For anyone else who gets stuck at this. Even though the topic is about creating a test class, and all the work on the topic is about creating a test factory, the challenge is about just creating a simple class (not just the method) as a normal class without @isTest. They took time to exclusively mention it for the Method, but didn't say anything about the class itself.

I noticed this when I randomly looked at the logs after clicking the button that it was trying to execute the class without a test context.

Although I see that Satyanarayana Pusuluri has a line in his question saying that the Apex class should not use it. But as of today (Apr 17, 2021) it doesn't have it. 


Hope this helps.
--Javed
Osith Rajanayake 3Osith Rajanayake 3
Remove the @isTest from the class then it might fix the issue and try out folllowing code.
 
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));
             }
       return cons;
     }
}

 
Varalakshmi Niharika JaguVaralakshmi Niharika Jagu
Try the below code and get 100% in your challenge!
 
public with sharing class RandomContactFactory {
    public static List<Contact> generateRandomContacts(Integer numContacts, String lName) {
        List<Contact> cons = new List<Contact>();
        for(Integer i=0; i<numContacts; i++) {
            Contact c = new Contact(LastName = lName,
                                   	FirstName = 'Test ' + i);
            cons.add(c);
        }
        return cons;
    }
}

 
Gürbey DemirtürkGürbey Demirtürk
I originally started the i from 1 and it did not work. That's why I am here :)

public class RandomContactFactory {
    public static List<Contact> generateRandomContacts(Integer numCnt, String lastName){
        List<Contact> cnt = new List<Contact>();
        for(Integer i=0; i < numCnt; i++) { // If you start the i from 1 since the instructions says Test1, Test2, it will not work
            Contact c = new Contact(FirstName='Test' + i, LastName = lastName);
            cnt.add(c);
        }
        return cnt;
    }
}
rohan danwaderohan danwade
public class RandomContactFactory {
    public static List<Contact> generateRandomContacts (integer para,string Ln){
        List<contact> emtToFullContact = new list<contact>();
        
        for(integer i=0;i<para;i++){
            contact con = new contact();
            con.Firstname= 'test'+i;
            con.Lastname= Ln;
            
            emtToFullContact.add(con);
            
        }return emtToFullContact;
    }
    
    
}