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
Swaroopa Akula 1Swaroopa Akula 1 

Test class for the opportunity class

Please help me writing a test class for the below class:

public class portallist{

        public List<Opportunity> getAcceptedList(){
        User u =[SELECT Email, Username FROM User WHERE Id =: UserInfo.getUserId()];
        String usrEmailId= u.Email;

        System.debug('*** Controller Logged in Users Email ID..' + usrEmailId +'**** username' + u.Username);
        List<Opportunity> oppList = [SELECT Partner_lead_Unique_number__c, Name, CloseDate, Account.Name, Opportunity_Accepted_Date__c, Deal_Reg_Expiration_Date__c
                                     FROM Opportunity 
                                     WHERE Portal_User_Email_ID__c=: usrEmailId AND Accept_Opportunity__c ='Accept'];
    
        return oppList;
    }
Best Answer chosen by Swaroopa Akula 1
Raj VakatiRaj Vakati
Try this code .. add other required fields 
 
@isTest
private class portallistTestCLass {

    static TestMethod void myUnitTest()
	{
		Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsconditions1234423@demooo.com',
            Alias = 'batman',
            Email='testtermsconditions1234423@demooo.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
			
		Account acc = new Account();
			acc.Name ='Test';
			// Add all required field
		insert acc;
		
		Contact cont = new Contact();
			cont.LastName ='Test';
			cont.accountId = acc.id;
		insert cont;
		
		Opportunity testOpportunity = new Opportunity(
	            Name = 'Test Opportunity Triggers',
	            CloseDate = System.today()+10,
                  Amount=123,
Portal_User_Email_ID__c=	'testtermsconditions1234423@demooo.com',
Accept_Opportunity__c ='Accept',			  
	            StageName = 'Closed Won',
	            accountId = acc.id
        );
		insert testOpportunity;
		
		
		Opportunity testOpportunity1 = new Opportunity(
	            Name = 'Test Opportunity Triggers',
	            CloseDate = System.today()+10,
                  Amount=123,
Portal_User_Email_ID__c=	'testtermsconditions1234423@demooo.com',
Accept_Opportunity__c ='',			  
	            StageName = 'Closed Won',
	            accountId = acc.id
        );
		insert testOpportunity1;
		
		Opportunity testOpportunity11 = new Opportunity(
	            Name = 'Test Opportunity Triggers',
	            CloseDate = System.today()+10,
                  Amount=123,
Portal_User_Email_ID__c=	'testtermsconditions1234423@demooo.com',
Accept_Opportunity__c ='Reject',			  
	            StageName = 'Closed Won',
	            accountId = acc.id
        );
		insert testOpportunity11;
		
		Test.startTest();
				
			portallist p = new portallist();
			p.getAcceptedList() ;
			p.getConvertedList() ;
			p.getRejectedList() ;
			p.getAcceptedList() ;
			
			
		Test.stopTest();
		}
    }
}

 

All Answers

Raj VakatiRaj Vakati
Try this code .. add other required fields 
 
@isTest
private class portallistTestCLass {

    static TestMethod void myUnitTest()
	{
		Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsconditions1234423@demooo.com',
            Alias = 'batman',
            Email='testtermsconditions1234423@demooo.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
			
		Account acc = new Account();
			acc.Name ='Test';
			// Add all required field
		insert acc;
		
		Contact cont = new Contact();
			cont.LastName ='Test';
			cont.accountId = acc.id;
		insert cont;
		
		Opportunity testOpportunity = new Opportunity(
	            Name = 'Test Opportunity Triggers',
	            CloseDate = System.today()+10,
                  Amount=123,
Portal_User_Email_ID__c=	'testtermsconditions1234423@demooo.com',
Accept_Opportunity__c ='Accept',			  
	            StageName = 'Closed Won',
	            accountId = acc.id
        );
		insert testOpportunity;
		
		
		Opportunity testOpportunity1 = new Opportunity(
	            Name = 'Test Opportunity Triggers',
	            CloseDate = System.today()+10,
                  Amount=123,
Portal_User_Email_ID__c=	'testtermsconditions1234423@demooo.com',
Accept_Opportunity__c ='',			  
	            StageName = 'Closed Won',
	            accountId = acc.id
        );
		insert testOpportunity1;
		
		Opportunity testOpportunity11 = new Opportunity(
	            Name = 'Test Opportunity Triggers',
	            CloseDate = System.today()+10,
                  Amount=123,
Portal_User_Email_ID__c=	'testtermsconditions1234423@demooo.com',
Accept_Opportunity__c ='Reject',			  
	            StageName = 'Closed Won',
	            accountId = acc.id
        );
		insert testOpportunity11;
		
		Test.startTest();
				
			portallist p = new portallist();
			p.getAcceptedList() ;
			p.getConvertedList() ;
			p.getRejectedList() ;
			p.getAcceptedList() ;
			
			
		Test.stopTest();
		}
    }
}

 
This was selected as the best answer
Swaroopa Akula 1Swaroopa Akula 1
perfect!It worked ! thanks
Swaroopa Akula 1Swaroopa Akula 1
Can you also give me the test class for the below trigger: creating a portal user 
/*****************************************************************************
    Name: PortalUserCreation 
    Usage: This trigger is used to send mail to Portal User which are created 
           from Self Registration Object    
****************************************************************************/
trigger PortalUserCreation on Self_Register_User_Request__c (before update) {

    /*if (!Test.isRunningTest()) { 
        /*if (!UtilClass.runOnce()) {
            return;
        }
    }*/
    
    /*String STATUS = 'Approved' ;*/
    String DUMMY_ACCOUNT  = 'Dummy Account' ;
    List<Contact> conListToInsert = new List<Contact>();
    /*//key = Self registration id && Value= License Id
    Map<Id, String> licenseMap = new Map<Id, String>();*/
    //key = Serf registration id && Value= Email Id
    Map<Id, String> emailMap = new Map<Id, String>();
    Map<Id, Self_Register_User_Request__c> dummyMap = new Map<Id, Self_Register_User_Request__c>();
    
    for(Self_Register_User_Request__c sr :trigger.new) { 
        System.debug('here is FN: '+sr.FirstName__c);
        System.debug('here is FN: '+sr.LastName__c);
        System.debug('here is FN: '+sr.Email__c);
        System.debug('here is FN: '+sr.AccountName__c);
        if(sr.FirstName__c == null || sr.LastName__c == null || sr.Email__c == null)  
            continue;
       /* if(sr.Status__c != null && sr.Status__c.equals(STATUS)){*/
           if(sr.Is_it_Approved__c  = TRUE){
            if(sr.AccountName__c != null ){
                Contact conRecord = new Contact(
                    FirstName = sr.FirstName__c,
                    LastName = sr.LastName__c,
                    Email = sr.Email__c,
                    AccountId = sr.AccountName__c
                );              
                System.debug('adding contact from line 36');
                conListToInsert.add(conRecord); 
            }
           /* if(sr.License_ID__c != null){
                licenseMap.put(sr.Id, sr.License_ID__c);       
            }*/
            if(sr.Email__c != null){
                emailMap.put(sr.Id, sr.Email__c);           
            }
            
            dummyMap.put(sr.Id, sr);                    
        }
    }
    //create Portal User
    if(conListToInsert != null && conListToInsert.size() > 0) {
        insert conListToInsert;
        List<Profile> pList = [select id from Profile where Name = 'Partner Community Login User'];
        if(!pList.isEmpty()){
            Profile p = pList[0];
            List<User> userListToInsert = new List<User>();
            for(Contact con :conListToInsert) {             
                String alias1 = '';
                if(con.FirstName.length() >= 0)
                    alias1 = con.FirstName.substring(0,1);
                    
                String alias2 = '';
                if(con.LastName.length() >= 4){
                    alias2 = con.LastName.substring(0, 4);        
                }else{
                    alias2 = con.LastName;
                }
                String alias = alias1 + alias2;
                User u = new User(
                    Alias = alias, 
                    Email = con.Email,
                    EmailEncodingKey = 'UTF-8', 
                    FirstName = con.FirstName,
                    LastName = con.LastName, 
                    LanguageLocaleKey = 'en_US', 
                    LocalesIdKey = 'en_US', 
                    ProfileId = p.Id, 
                    ContactId = con.id,
                    TimeZonesIdKey = 'America/Los_Angeles', 
                    UserName = con.Email
                );
                Database.DMLOptions dmo = new Database.DMLOptions();
                dmo.EmailHeader.triggerUserEmail = true;
                u.setOptions(dmo);
                userListToInsert.add(u);
            }
                
            Database.SaveResult[] results = database.insert(userListToInsert, false);
            for(Database.SaveResult sr :results){
               if(!sr.isSuccess()){
                  Database.Error err = sr.getErrors()[0];
                  throw new CustomException(err.getMessage());
                 /* break;*/
               }
            }                       
        }        
    }  
    
   
    //define your custom exception
    public class CustomException extends Exception{}
    
}
Raj VakatiRaj Vakati
Can you give me code to insert the Self_Register_User_Request__c  object ..and give me basic test class with Self_Register_User_Request__c insert 
Swaroopa Akula 1Swaroopa Akula 1
Below is the test data for the self registration object
Self_Register_User_Request__c  selfregister = selfregister(FirstName__c='Sree',
                                                                       LastName__c='Chandra',
                                                                       Email__c='Test@gmail.com',
                                                                       Company_web_site__c='WWW.DST.com',
                                                                       Company__c='DST',
                                                                       AccountName__c='direct')
Raj VakatiRaj Vakati
@isTest
private class portallistTestCLass {

    static TestMethod void myUnitTest()
	{
		Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsconditions1234423@demooo.com',
            Alias = 'batman',
            Email='testtermsconditions1234423@demooo.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
			
		
		
		Test.startTest();
			Self_Register_User_Request__c  selfregister = selfregister(FirstName__c='Sree',
                                                                       LastName__c='Chandra',
                                                                       Email__c='Test@gmail.com',
                                                                       Company_web_site__c='WWW.DST.com',
                                                                       Company__c='DST',
                                                                       AccountName__c='direct');
																	   
																	   insert selfregister ;
																	   
																	   selfregister.Is_it_Approved__c  =true ; 
																	   selfregister.Status__c='New';
																	   update selfregister ;
																	   
																	   
			
			
		Test.stopTest();
		}
    }
}

 
Raj VakatiRaj Vakati
@isTest
private class PortalUserCreationTest {

    static TestMethod void myUnitTest()
	{
		Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsconditions1234423@demooo.com',
            Alias = 'batman',
            Email='testtermsconditions1234423@demooo.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
			
		
		
		Test.startTest();
			Self_Register_User_Request__c  selfregister = selfregister(FirstName__c='Sree',
                                                                       LastName__c='Chandra',
                                                                       Email__c='Test@gmail.com',
                                                                       Company_web_site__c='WWW.DST.com',
                                                                       Company__c='DST',
                                                                       AccountName__c='direct');
																	   
																	   insert selfregister ;
																	   
																	   selfregister.Is_it_Approved__c  =true ; 
																	   selfregister.Status__c='New';
																	   update selfregister ;
																	   
																	   
			
			
		Test.stopTest();
		}
    }
}

 
Swaroopa Akula 1Swaroopa Akula 1
Getting an error:  Accountname__c is a look up field...i tthink that is the reason i am getting error. 
Method NamemyUnitTest
Pass/FailFail
Error MessageSystem.StringException: Invalid id: direct
Stack TraceClass.PortalUserCreationTest.myUnitTest: line 40, column 1



@isTest
private class PortalUserCreationTest {

    static TestMethod void myUnitTest()
    {
        Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsconditions1234423@demooo.com',
            Alias = 'batman',
            Email='testtermsconditions1234423@demooo.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
            
        
        
        Test.startTest();
            Self_Register_User_Request__c  selfregister =  new Self_Register_User_Request__c ();
                                                                       selfregister.FirstName__c='Sree';
                                                                       selfregister.LastName__c='Chandra';
                                                                       selfregister.Email__c='Test@gmail.com';
                                                                       selfregister.Company_web_site__c='WWW.DST.com';
                                                                       selfregister.Company__c='DST';
                                                                       selfregister.AccountName__c='direct';
                                                                       
                                                                       insert selfregister ;
                                                                       
                                                                       selfregister.Is_it_Approved__c  =true ; 
                                                                       //selfregister.Status__c='New';
                                                                       update selfregister ;
                                                                       
                                                                       
            
            
        Test.stopTest();
        }
    }
}
Swaroopa Akula 1Swaroopa Akula 1
i think need to create a account right first and then add the account id here? correct?
Raj VakatiRaj Vakati
Account is looks up so you need to insert account first and pass that refernce to accountdiret 
Swaroopa Akula 1Swaroopa Akula 1
I have  inserted the account info. The test class is passed but no code coverage.
@isTest
private class PortalUserCreationTest {

    static TestMethod void myUnitTest()
    {
        Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsconditions1234423@demooo.com',
            Alias = 'batman',
            Email='testtermsconditions1234423@demooo.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
        
        Account acc = new Account();
            acc.Name ='Test1';
            acc.Account_Type__c = 'Reseller';
            acc.New_Account_Source__c = 'Advertisement';

        insert acc;
            
        
        
        Test.startTest();
            Self_Register_User_Request__c  selfregister =  new Self_Register_User_Request__c ();
                                                                       selfregister.FirstName__c='Sree';
                                                                       selfregister.LastName__c='Chandra';
                                                                       selfregister.Email__c='Test@gmail.com';
                                                                       selfregister.Company_web_site__c='WWW.DST.com';
                                                                       selfregister.Company__c='DST';
                                                                       selfregister.AccountName__c= acc.id;
                                                                        selfregister.Is_it_Approved__c  =true ; 
                                                                       insert selfregister ;
                                                                       
                                                                       //selfregister.Is_it_Approved__c  =true ; 
                                                                       //selfregister.Status__c='New';
                                                                      // update selfregister ;
                                                                       
                                                                       
            
            
        Test.stopTest();
        }
    }
}




Can you please help me
Swaroopa Akula 1Swaroopa Akula 1
I am getting below error:
Error MessageSystem.DmlException: Update failed. First exception on row 0 with id a591g00000087sbAAA; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, PortalUserCreation: execution of BeforeUpdate

caused by: PortalUserCreation.CustomException: Duplicate Username.<br>The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). 

Trigger.PortalUserCreation: line 85, column 1: []
Stack TraceClass.PortalUserCreationTest.myUnitTest: line 64, column 1


But my code was covered to 95%
below is the test class


@isTest
private class PortalUserCreationTest {

    static TestMethod void myUnitTest()
    {
        Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'XYZanjkaeanflamdfldfaf123@test.com',
            Alias = 'batman',
            Email='testtermscon123dit123ions1234423@mycomany.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
        
        Account acc = new Account();
            acc.Name ='Test1';
            acc.Account_Type__c = 'Reseller';
            acc.New_Account_Source__c = 'Advertisement';

        insert acc;
            
        
        
        Test.startTest();
            Self_Register_User_Request__c  selfregister =  new Self_Register_User_Request__c ();
                                                                       selfregister.FirstName__c='Sree';
                                                                       selfregister.LastName__c='Chandra';
                                                                       selfregister.Email__c='Test@gmail.com';
                                                                       selfregister.Company_web_site__c='WWW.DST.com';
                                                                       selfregister.Company__c='DST';
                                                                       selfregister.AccountName__c= acc.id;
                                                                        selfregister.Is_it_Approved__c  =False ; 
                                                                       insert selfregister ;
            
            
           
                                                                        
                                                                        
                                                                        selfregister.AccountName__c= acc.id;
                                                                        selfregister.Is_it_Approved__c  =True ; 
                                                                       update selfregister;                                                      
                                                                       //selfregister.Is_it_Approved__c  =true ; 
                                                                       //selfregister.Status__c='New';
                                                                      // update selfregister ;
                                                                       
                                                                       
            
            
        Test.stopTest();
        }
    }
}
Please let me know how should i solve this
Swaroopa Akula 1Swaroopa Akula 1
@Raj Vakati
Could you please help me on this