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
Chris - ARIChris - ARI 

Test Class for Insert New Opportunity

Test Class keeps failing. What is wrong here?
 
@isTest
public class Test_OppWonChatter {
    static testMethod void insertNewOpportunity(){
        
        Account a = new Account(Name = 'Test');
        
        insert a;
        
        
        Opportunity o = new Opportunity();
        o.name = 'Test';
        o.AccountId = a.Id;
        o.StageName = 'Closed Won';
        o.CloseDate = date.today();
        o.Type = 'New Customers';
        
        insert o;
    }
}

 
Rakesh51Rakesh51
Looks good to me. What was the error ?
Chris - ARIChris - ARI
User-added image
Rakesh51Rakesh51
click on view and check the error reason 
Chris - ARIChris - ARI
Looks like that was initially caused by a validation error so I added a couple more fields but am still failing the test.
 
@isTest
public class Test_OppWonChatter {
    static testMethod void insertNewOpportunity(){
        
        Account a = new Account();
        a.Name = 'Test';
        a.Fleet_Size__c = 100;
        a.Industry = 'Retail';
        
        insert a;
        
        
        Opportunity o = new Opportunity();
        o.name = 'Test';
        o.AccountId = a.Id;
        o.StageName = 'Closed Won';
        o.CloseDate = date.today();
        o.Type = 'New Customers';
        
        insert o;
    }
}

User-added image
Suraj Tripathi 47Suraj Tripathi 47
Hi Chris,

"You can try this code."
@isTest
public class CreateNewOpportunityTest
{
    @isTest
    public static void OpportunityTestMethod()
    {
      try{
        Account accountObj = new Account();
        accountObj .Name = 'Account1';
        insert accountObj ;
        System.AssertEquals(accountObj.Name, 'Account1');
        
        Opportunity oppObj = new Opportunity();
        oppObj.Name = 'Opp1';
        oppObj.Accountid = accountObj.id;
        oppObj.StageName = 'Prospecting';
        oppObj.CloseDate = system.Today();
        insert oppObj;
        System.AssertEquals(oppObj.Name, 'Opp1');
      }catch(Exception e){
        System.debug('Exception due to--->: '+e.getMessage());
       }  
    }
}
If you find your Solution then mark this as the best answer. 

Thank you!

Regards 
Suraj Tripathi