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
dev_sfdc1dev_sfdc1 

Help for Test Class

Apex class:

public PageReference Save()
{
    service.Asset_Name__c =assetname;
    insert service;

   Task T = new Task();
        T.WhatId=assetname;
        T.WhoId=service.Employee__c;
        T.OwnerId= UserInfo.getUserId();

        insert T;

    PageReference ref= new PageReference('/'+assetname);
    ref.setredirect(true);
    return ref;
}


Test Class:

static TestMethod void ServiceRecordAssetTestClass()
    {
        PageReference ref = Page.ServiceRecord;
        Test.setcurrentPage(ref);

        Account acc = new Account(Name='Test');
        insert acc;

        Contact con = new Contact(LastName='Test2');
        insert con;

        Physical_Asset__c phy = new  Physical_Asset__c(Name='PhysicalAssetName',Vendor_Account__c=acc.id);
        insert phy;

        Service_Record__c testservice = new Service_Record__c(Name='Test Service',Employee__c=con.id,Asset_Name__c=phy.id);
        insert testservice;

        Task t = new Task(Subject='Task Name');
        insert t;

        ApexPages.CurrentPage().getParameters().put('retURL','/'+phy.Id);
        ApexPages.StandardController sc = new ApexPages.StandardController(testservice);

        ServiceRecordAsset  sr = new ServiceRecordAsset(sc);

        String nextPage=sr.Save().getUrl();-----------> Getting Error
        system.assertEquals('/'+phy.id,nextpage);

        //sr.save();
    }
}


Error is:

System.DmlException: Insert failed. First exception on row 0 with id a0ge0000000T3UqAAK; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

otherwise it covers 30%.

Please help me to resolve this error.
Ankit Gupta@ DeveloperAnkit Gupta@ Developer
Hi,

Try the below code snippet as reference:

public PageReference Save()
{
    service.Asset_Name__c =assetname;
    insert service;

   Task T = new Task();
        T.WhatId=assetname;
        T.WhoId=service.Employee__c;
        T.OwnerId= UserInfo.getUserId();

        insert T;

    PageReference ref= new PageReference('/'+assetname);
    ref.setredirect(true);
    return ref;
}


Test Class:
@isTest
public class saveMethodTestClass
{
static TestMethod void ServiceRecordAssetTestClass()
{
  className classobj=new className();
  classobj.assetname='test';
  classobj.Save();
 
}


Regards
Ankit Gupta