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
Tania B GarciaTania B Garcia 

Apex Test is complete but coverage is 0%

Hi
Help please, I made the following trigger on Opportunity, where to being in a specific stage, create a record of a random user of a specific profile in the Opportunity Team
This is my trigger
trigger SLInsertOppTeam on Opportunity (before insert, before update) {
	for(Opportunity opp : trigger.New){	
		if(opp.StageName == 'A' && opp.is_new__c == false)
		{
            List<OpportunityTeamMember> member = [SELECT TeamMemberRole FROM OpportunityTeamMember 
                                                  Where OpportunityId = : opp.Id
                                                 AND TeamMemberRole = : 'Analist'];
            if(member.size() == 0 )
            {
				OpportunityTeamMember OTM = new OpportunityTeamMember();
            	OTM.OpportunityId = opp.Id;
				OTM.TeamMemberRole = 'Analist';
				OTM.OpportunityAccessLevel = 'Edit';       
            	List<User> uList = [SELECT Id FROM User Where IsActive = true and ProfileId = '00e4x000000NCX0AAO'];
            	if(uList.size() > 0){
                	Integer Ran = (integer)(Math.random() * (uList.size()));
            		OTM.UserId = uList[Ran].id;
            	}
            	insert OTM; 
             }   
		}   
    }  
}
When doing the trigger test, there is no error and it completes it well, but in the coverage it stays at 0%, could you help me to know what is wrong in the test or know how I can improve it so that it gives me a percentage of coverage feasible for you to take it as good
This is my Test
@isTest
private class SLTestInsertOMT {
    @isTest(SeeAllData=true)
    static void TestInsert() 
    {
        Test.startTest();
        Opportunity opp = [select Id, StageName, is_new__c from Opportunity where id_sf__c = '21022600147' LIMIT 1];
        if(opp.StageName == 'A' && opp.is_new__c == false)
        {
        	OpportunityTeamMember otm = new OpportunityTeamMember (OpportunityId= opp.Id, 
                                                             TeamMemberRole = 'Analist',
                                                             OpportunityAccessLevel = 'Edit',
                                                             UserId ='0054x000004Hu2xAAC');
        	insert otm;
        }
        System.assert(true); 
        Test.stopTest();
    }
}


 
Best Answer chosen by Tania B Garcia
ravi soniravi soni
hi Taniya,
try this following apex class and test class with 100% coverage as well as best practice.
//Apex Trigger
trigger SLInsertOppTeam on Opportunity (after insert, after update) {
    if(trigger.isAfter){
        if(trigger.isInsert || trigger.isUpdate){
    set<Id> setOppIds = new set<Id>();
        list<OpportunityTeamMember> lstOpportunityTeamMember = new  list<OpportunityTeamMember>();
        
        for(Opportunity opp : trigger.New){	
        //if(opp.StageName == 'close Won'){
          if(opp.StageName == 'A' && opp.is_new__c == false){
            setOppIds.add(opp.Id);
            }
	}
        List<OpportunityTeamMember> OppTeamMember = [SELECT TeamMemberRole FROM OpportunityTeamMember 
                                                      Where OpportunityId IN : setOppIds
                                                      AND TeamMemberRole ='Analist'];
        
        if(OppTeamMember.size() == 0){
            Profile oProfile = [Select Id From Profile Where Name= 'System Administrator' Limit 1];

            List<User> uList = [SELECT Id FROM User Where IsActive = true and ProfileId =: oProfile.Id];
            for(Opportunity opp : trigger.New){	
             	OpportunityTeamMember newOppTeamMember = new OpportunityTeamMember();
            	newOppTeamMember.OpportunityId = opp.Id;
				newOppTeamMember.TeamMemberRole = 'Analist';
				newOppTeamMember.OpportunityAccessLevel = 'Edit';
                
            	
            	if(uList.size() > 0){
                	Integer Ran = (integer)(Math.random() * (uList.size()));
            		newOppTeamMember.UserId = uList[Ran].Id;
            	}
            	lstOpportunityTeamMember.add(newOppTeamMember);
                }   
        }
        if(lstOpportunityTeamMember.size() > 0){ 
            insert lstOpportunityTeamMember;
        }
    }
    }
        
}
 
/* Test Class */
@isTest
public class SLInsertOppTeamTest {
@isTest
    public static void insertOpp(){
        Opportunity opp = new Opportunity();
        opp.Name = 'test';
        //Opp.StageName = 'close won';
        Opp.StageName = 'A';
        Opp.is_new__c = false;
        Opp.CloseDate = system.today();
        insert opp;
        test.startTest();
        opp.Name = 'test 1';
        update opp;
        test.stopTest();
        system.assertEquals('test 1', opp.Name);
       }
}

let me know if it helps you and don't forget to make it as best.
Thank You
 

All Answers

Maharajan CMaharajan C
Hi Gracia,

You trigger needs to be bulkified:

1. Don't use the SOQL Queries , DML Statements inside for loop.
2. Don't use the hardcoded record id's in trigger. use the profile name to query the user in below line.
    List<User> uList = [SELECT Id FROM User Where IsActive = true and ProfileId = '00e4x000000NCX0AAO']; change to below line
    List<User> uList =  [ SELECT Id FROM User Where IsActive = true and Profile.Name = 'System Administrator' ];
3. In test class don't use the (SeeAllData=true). Instead of that create test data in test class.
4. Use after contexts in trigger while you performing the actions in related objects.

Please try the below trigger:
 
trigger SLInsertOppTeam on Opportunity (after insert, after update) {
    Map<Id,List<OpportunityTeamMember>> oppMemberMap = new Map<Id,List<OpportunityTeamMember>>();
    set<Id> oppIds = new set<Id>();
    List<OpportunityTeamMember> otmList = new List<OpportunityTeamMember>();
    List<User> uList = [SELECT Id FROM User Where IsActive = true and ProfileId = '00e4x000000NCX0AAO'];
    for(Opportunity opp : trigger.New){
        if(opp.StageName == 'A' && opp.is_new__c == false)
        {
            oppIds.add(opp.Id);
        }
    }
    
    for ( OpportunityTeamMember member : [SELECT Id,OpportunityId,TeamMemberRole FROM OpportunityTeamMember Where OpportunityId IN: oppIds AND TeamMemberRole = : 'Analist']){
        if(!oppMemberMap.containsKey(member.OpportunityId)){
            oppMemberMap.put(member.OpportunityId, new List<OpportunityTeamMember>{member});
        }
        else{
            oppMemberMap.get(member.OpportunityId).add(member);
        }
    }
    
    for(Opportunity opp : trigger.New){
        if(opp.StageName == 'A' && opp.is_new__c == false)
        {
                List<OpportunityTeamMember> oppMemberList = new List<OpportunityTeamMember>();
                if(oppMemberMap.containsKey(opp.Id)){
                    oppMemberList = oppMemberMap.get(opp.Id);
                }
                if(oppMemberList.size() == 0 )
                {
                    OpportunityTeamMember OTM = new OpportunityTeamMember();
                    OTM.OpportunityId = opp.Id;
                    OTM.TeamMemberRole = 'Analist';
                    OTM.OpportunityAccessLevel = 'Edit';
                    if(uList.size() > 0){
                        Integer Ran = (integer)(Math.random() * (uList.size()));
                        OTM.UserId = uList[Ran].id;
                    }
                    otmList.add(OTM);
                }
        }
    }
    
    if(!otmList.isEmpty()){
        insert otmList;
    }
}

Test Class:

I assumed opp.is_new__c field become as false in opp update so i have updated the opp in below test class. Otherwise you can remove the update statement below.
@isTest
public class SLInsertOppTeamTest {
	static testmethod void testSLInsertOppTeam(){
        Account testAccount = new Account();
        testAccount.Name='Test Account record' ;
        insert testAccount;
        
        // Add if there is any other Mandatory fields in Opportunity.
        Opportunity opp = new Opportunity();
        opp.name='oppname';
        opp.accountid=testAccount.id;
        opp.CloseDate=system.today().addDays(30);
        opp.StageName='A';
		opp.is_new__c == false;  // If this a formula field then remove it. 
		insert opp;
        test.startTest();
			opp.name='testoppname';
			update opp;
        test.stopTest();
    }
}


Thanks,
Maharajan.C

 
Suraj Tripathi 47Suraj Tripathi 47


Hi Tania,

Please find the Solution. "Apex Test is complete but coverage is 0%"

  If you are writing a test class for trigger then you no need to write Test.startTest() and Test.stopTest(); like you have written a trigger on Opportunity Insert then as you run test class it automatically fires the trigger because you have inserted opportunity in test class.

Here is the test class of your code with 100% coverage.

@isTest
public class ExampleOpportunityTest {
    @isTest
    public static void TestInsert(){
        Opportunity opInstance=new Opportunity();
        opInstance.StageName='A';
        opInstance.is_new__c=false;
        opInstance.Name='Test';
        opInstance.CloseDate=Date.today();
        Insert opInstance;
        
        UserRole r = new UserRole(DeveloperName = 'MyCustomRole', Name = 'My Role');
        insert r;
        
        
        User u = new User(
            ProfileId ='00e2y000000RhmjAAC',
            isActive=true,
            LastName = 'last',
            Email = 'puser000@amamama.com',
            Username = 'puser000@amamama.com' + System.currentTimeMillis(),
            CompanyName = 'TEST',
            Title = 'title',
            Alias = 'alias',
            TimeZoneSidKey = 'America/Los_Angeles',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US',
            UserRoleId = r.Id
        );
        insert u;
        OpportunityTeamMember otmInstance=new OpportunityTeamMember();
        otmInstance.OpportunityId=opInstance.id;
        otmInstance.UserId=u.id;
        otmInstance.TeamMemberRole='Analist';
        insert otmInstance;
        
    }
}


Please let me know it is working or not.

Please mark Best Answer so that other people would take reference from it.

Thanks

ravi soniravi soni
hi Taniya,
try this following apex class and test class with 100% coverage as well as best practice.
//Apex Trigger
trigger SLInsertOppTeam on Opportunity (after insert, after update) {
    if(trigger.isAfter){
        if(trigger.isInsert || trigger.isUpdate){
    set<Id> setOppIds = new set<Id>();
        list<OpportunityTeamMember> lstOpportunityTeamMember = new  list<OpportunityTeamMember>();
        
        for(Opportunity opp : trigger.New){	
        //if(opp.StageName == 'close Won'){
          if(opp.StageName == 'A' && opp.is_new__c == false){
            setOppIds.add(opp.Id);
            }
	}
        List<OpportunityTeamMember> OppTeamMember = [SELECT TeamMemberRole FROM OpportunityTeamMember 
                                                      Where OpportunityId IN : setOppIds
                                                      AND TeamMemberRole ='Analist'];
        
        if(OppTeamMember.size() == 0){
            Profile oProfile = [Select Id From Profile Where Name= 'System Administrator' Limit 1];

            List<User> uList = [SELECT Id FROM User Where IsActive = true and ProfileId =: oProfile.Id];
            for(Opportunity opp : trigger.New){	
             	OpportunityTeamMember newOppTeamMember = new OpportunityTeamMember();
            	newOppTeamMember.OpportunityId = opp.Id;
				newOppTeamMember.TeamMemberRole = 'Analist';
				newOppTeamMember.OpportunityAccessLevel = 'Edit';
                
            	
            	if(uList.size() > 0){
                	Integer Ran = (integer)(Math.random() * (uList.size()));
            		newOppTeamMember.UserId = uList[Ran].Id;
            	}
            	lstOpportunityTeamMember.add(newOppTeamMember);
                }   
        }
        if(lstOpportunityTeamMember.size() > 0){ 
            insert lstOpportunityTeamMember;
        }
    }
    }
        
}
 
/* Test Class */
@isTest
public class SLInsertOppTeamTest {
@isTest
    public static void insertOpp(){
        Opportunity opp = new Opportunity();
        opp.Name = 'test';
        //Opp.StageName = 'close won';
        Opp.StageName = 'A';
        Opp.is_new__c = false;
        Opp.CloseDate = system.today();
        insert opp;
        test.startTest();
        opp.Name = 'test 1';
        update opp;
        test.stopTest();
        system.assertEquals('test 1', opp.Name);
       }
}

let me know if it helps you and don't forget to make it as best.
Thank You
 
This was selected as the best answer
Tania B GarciaTania B Garcia
Hi
Thank you very much Maharajan C, Suraj Tripathi 47 and veer soni, for your help, I read all your comments, but I did my adjustments and the test regarding what I said veer soni

In the end the test turned out to fail because he sent me the following "Methods defined as TestMethod do not support Web service callouts", but in the coverage it gave me 100%

Regards