Showing posts with label Test Class. Show all posts
Showing posts with label Test Class. Show all posts

Tuesday, 18 July 2017

How to write test class for Scheduler /Schedulable class in Salesforce



Sample Batch job

global class AccountUpdateBatchJob implements Database.Batchable<sObject> 
{    
    global Database.QueryLocator start(Database.BatchableContext BC)     {
        String query = 'SELECT Id,Name FROM Account';                
        return Database.getQueryLocator(query);     
    }    
    global void execute(Database.BatchableContext BC, List<Account> scope)     {        
        for(Account a : scope)        
        {            
            a.Name = a.Name + 'Updated by Batch job';        
        }        
        update scope;       
    }    
    global void finish(Database.BatchableContext BC) {    }
}



Scheduler Class For Batch Apex


global class AccountUpdateBatchJobscheduled implements Schedulable 
{
    global void execute(SchedulableContext sc) 
    {
        AccountUpdateBatchJob b = new AccountUpdateBatchJob(); 
        database.executebatch(b);
    }
}




Test Class for Scheduler Class


@isTest
private class AccountUpdateBatchJobscheduledTest
{

    static testmethod void schedulerTest() 
    {
        String CRON_EXP = '0 0 0 15 3 ? *';
        
        // Create your test data
        Account acc = new Account();
        acc.name= 'test';
        insert acc;
        
        Test.startTest();

            String jobId = System.schedule('ScheduleApexClassTest',  CRON_EXP, new AccountUpdateBatchJobscheduled());
            CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
            System.assertEquals(CRON_EXP, ct.CronExpression);
            System.assertEquals(0, ct.TimesTriggered);

        Test.stopTest();
        // Add assert here to validate result
    }
}



Please check below post for Batch job
1) http://amitsalesforce.blogspot.com/2016/02/batch-apex-in-salesforce-test-class-for.html



Please check below post for more detail
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm


Thanks,
Amit Chaudhary




Friday, 10 February 2017

Salesforce Tutorial | How to learn Test class | Test Class Best Pratice | Sample Test class | Test Factory


Apex Unit Tests

In Salesforce , the code must have 75% code coverage to be deploy in Production. This code coverage is performed by the test classes. Please check below post to learn about test classes in salesforce :-


1) Apex Testing



Please check above Trailhead module to learn more about test classes.

2) Best Practice for Test classes | Sample Test class

http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Please check above post to see how to write test class for Trigger , Standard Controller , Controller and StandardSetController . With Test Class best practice. 


3) Test Utility Classes | TestDataFactory | Util Test in salesforce

 

http://amitsalesforce.blogspot.com/2017/01/test-utility-classes-testdatafactory.html

Test utility classes contain reusable code for test data creation. Please check above post for How to create Test Data Factory in salesforce with example.

4) Test classes with @isTest

http://amitsalesforce.blogspot.com/2015/09/test-classes-with-istest.html

Please check above post for  @isTest annotation uses and Limitation.

5) StartTest and stopTest Method

 

StartTest and StopTest are standard test methods which are available for test classes. Please check above post for StartTest and StopTest Method uses and Limitation.  


6) Salesforce Testing Best Practice Guidelines | Unit Test Mechanism in Salesforce | Test Methods

Please check above post for Unit Test Mechanism in Salesforce and for Test class Best practice.


7) Code Coverage Report in excel Format | Test Class Result in XLS
http://amitsalesforce.blogspot.com/2015/09/code-coverage-report-in-excel-format.html

Some time we need to Download/Export the code coverage for each class in excel file . So same we can use the Code Coverage Report App. Please check above post for same

 

 

8) @testSetup ( Set Up Test Data for an Entire Test Class )


Please check above post how to create test data for entire test class.

 


 

Thanks,

Amit Chaudhary

 

Friday, 27 January 2017

Test Utility Classes | TestDataFactory | Util Test in salesforce


Common test utility classes are public test classes that contain reusable code for test data creation.The TestDataFactory/ testutility  class is a special type of class — It is a public class that is annotated with @isTest and and as such, are excluded from the organization code size limit and execute in test context and can be accessed only from a running test.

Test utility classes/TestDataFactory contain methods that can be called by test methods to perform useful tasks, such as setting up test data.


Step 1:- Create TestDataFactory / Test utility
@isTest
public with sharing class TestDataFactory 
{
    /** 
    * ********************************************************
    * This method is test data for create Lead
    * ********************************************************
    */

    public static Lead createLead(Boolean doInsert)
    {
        Lead newLead = new Lead() ;
        newLead.FirstName = 'Cole';
        newLead.LastName = 'Swain';
        newLead.Company = 'BlueWave';
        newLead.Status = 'contacted';
        if(doInsert){
            insert newLead;
        }
        return newLead;
    }

    public static Void convertLead(Lead newLead )
    {
        database.leadConvert lc = new database.leadConvert();
        lc.setLeadId(newLead.id);
        leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        lc.setOpportunityName('Cole Swain');
        
    }
        
    /** 
    * ******************************************************
    * This method is test data for create Account
    * ******************************************************
    */
    
    public static Account createAccount(Boolean doInsert)
    {
        Account acc = new Account();
        acc.Name = 'Test Account';
        if(doInsert){
            insert acc;
        }
        return acc;
    }
       
     /**
     * *******************************************************
     * This method is test data for create contact object
     * *******************************************************
     */
    public static Contact createContact(Boolean doInsert)
    {
        return createContact(doInsert, createAccount(true).Id);
    }
    
    public static Contact createContact(Boolean doInsert, Id accId)
    {
        Contact con = new Contact();
        con.AccountId = accId;
        con.FirstName = 'FirstName';
        con.LastName = 'LastName';
        con.Email = 'FirstName@test.com' + Math.floor(Math.random() * 1000);
        if(doInsert)
        {
            insert con;
        }
        return con;
    }

    /**
    * ***********************************************************
    * This method is test data for create Opportunity object
    * ***********************************************************
    */
    
    public static Opportunity createOpportunity(Boolean doInsert, Id accId)
    {
        Opportunity oppt = new Opportunity(Name ='New mAWS Deal',
                            AccountID = accId,
                            StageName = 'Customer Won',
                            Amount = 3000,
                            CloseDate = System.today()
                            );
        if(doInsert)
        {
            insert oppt;
        }
        return oppt;
    }   
    
    /**
    * ************************************************************
    * This method is test data for create Case object
    * ************************************************************
    */
        
    public static Case  createCase(Boolean doInsert )
    {
        Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email');
        if(doInsert)
        {
            insert cas ;
        }
        return cas ;
    }    
    
}



Step 2:- How to Use TestDataFactory / Test utility

@isTest
private class MyTestClass 
{
    static testmethod void myUnitTest() 
    {
        Lead leadObj = TestDataFactory.createLead(true);
        Account accObj = TestDataFactory.createAccount(true);
        Contact contObj = TestDataFactory.createContact(true,accObj.id);
        Opportunity oppObj = TestDataFactory.createOpportunity(true,accObj.id);
        Case caseObj = TestDataFactory.createCase(true);
    }
    // If you want to edit data according to apex class then try like below
    static testmethod void myUnitTest1() 
    {
        Lead leadObj = TestDataFactory.createLead(false); // pass false
        leadObj.LastName ='MyName';
        insert leadObj ;
        
        Account accObj = TestDataFactory.createAccount(false);
        accObj.Name ='MyName';
        insert accObj;
        
    }
    
}


Please check below post for Test Class Sample :-



Some Useful link :-

1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_utility_classes.htm
2) https://trailhead.salesforce.com/en/apex_testing/apex_testing_data?id=apex_testing
3) https://github.com/dhoechst/Salesforce-Test-Factory


Thanks
Amit Chaudhary
@amit_sfdc

Sunday, 20 September 2015

Code Coverage Report in excel Format | Test Class Result in XLS





Now you can view the overall and individual entity code coverage in your organization. The results of the code coverage can be downloaded in Excel format

For Same you Can install the below App Exchange Product


Code Coverage Report

https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000DXzlpEAD

How to configure the App. 
Please check below link for same.
https://appexchange.salesforce.com/servlet/servlet.FileDownload?file=00P3000000Qq5GkEAJ

How To Configure This APP

You can check the Setup step in Installation and Configuration Tab



Step 1:- Setup Remote Site Setting

Add a value for Remote site setting (In same org in which package is installed)
Goto Setup > Administration Setup > Security Controls > Remote Site Settings Add value to your Salesforce instance, for example  'https://na34.salesforce.com’



Step 2 Setup Base URL

Please set your Base URL.
Go to Setup > Develop > Custom Settings > Code Coverage Configuration > Manage > New. Set the name to 'baseUrl' and the value to your Salesforce instance, for example 'https://ap2.salesforce.com'

à Open Custom Setting and Click on Code Coverage Configuration 


à Then click on Manage


à Then click on Manage and then New Button and then Enter the below detail
Name as :- baseUrl

(Please enter your org base url.)






Thursday, 3 September 2015

Test classes with @isTest

Use the isTest annotation to define classes and methods that only contain code used for testing your application. The isTest annotation on methods is equivalent to the testMethod keyword.

  1. Classes and methods defined as isTest can be either private or public. Classes defined as isTest must be top-level classes.
  2. One advantage to creating a separate class for testing is that classes defined with isTest don't count against your organization limit of 3 MB for all Apex code.
  3. You can also add the @isTest annotation to individual methods
  4. Classes defined as isTest can't be interfaces or enums
  5. Methods of a test class can only be called from a running test, that is, a test method or code invoked by a test method, and can't be called by a non-test request.
  6. Test methods can’t be used to test Web service callouts. Instead, use mock callouts
  7. You can’t send email messages from a test method
  8. Methods of a public test class can only be called from a running test, that is, a test method or code invoked by a test method, and can't be called by a non-test request.

@isTest
                    
private class MyTestClass {
   @isTest static void test1() {
      // Implement test code
   }
   @isTest static void test2() {
      // Implement test code
   }
}

IsTest(SeeAllData=true) Annotation

use the isTest(SeeAllData=true) annotation to grant test classes and individual test methods access to all data in the organization,

  1. If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test methods whether the test methods are defined with the @isTest annotation or the testmethod keyword
  2. The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method leve

IsTest(OnInstall=true) Annotation

Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This annotation is used for tests in managed or unmanaged packages


Saturday, 6 June 2015

Best Practice for Test classes | Sample Test class

In this post we will talk about best practice for test classes with test class examples in Salesforce. We will also talk about how to write Salesforce test class for controller, test class for Standard Controller, test class for trigger in salesforce with example.

What to Test In Apex?

Salesforce.com recommends the following components need to test.

1. Single Records: 

This includes testing to verify that a single record produces the correct, expected result

2. Bulk Records: 

Any apex code, whether a triggers, a class or on extension may be used for 1to 200 records we must test not only the single record case, but the bulk cases as well.

3. Positive scenarios: 

This type of component testing expect a system to save a record without error.

4. Negative scenarios: 

This type of component testing expect a system to give error.

5. Restricted User: 

Test whether a user with restricted access to the objects used in code sees the expected behavior, i.e whether they can run the code or receive error messages.


Here Example of Test Classes



Test Class for Trigger


@isTest 
public class TriggerTestClass 
{
    static testMethod void testMethod1() 
 {
  // Perform DML here only
 
        }
}

Test Class for Standard Controller


@isTest 
public class ExtensionTestClass 
{
 static testMethod void testMethod1() 
 {
 Account testAccount = new Account();
 testAccount.Name='Test Account record' ;
 insert testAccount;

 Test.StartTest(); 
  ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
  myControllerExtension testAccPlan = new myControllerExtension(sc);

  PageReference pageRef = Page.AccountPlan; // Add your VF page Name here
  pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
  Test.setCurrentPage(pageRef);

  //testAccPlan.save(); call all your function here
 Test.StopTest();
 }
}


Test Class for Controller class


@isTest 
public class ControllerTestClass 
{
 static testMethod void testMethod1() 
 {
 Account testAccount = new Account();
 testAccount.Name='Test Account record' ;
 insert testAccount;

 Test.StartTest(); 

  PageReference pageRef = Page.AccountPlan; // Add your VF page Name here
  pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
  Test.setCurrentPage(pageRef);

  myController testAccPlan = new myController();
  
  //testAccPlan.save(); call all your function here
 Test.StopTest();
 }
}


Test Class for StandardSetController


@isTest 
public class TestStandardSetController 
{
 static testMethod void testMethod1() 
 {
 List <Account> lstAccount = new List<Account>();
 
 Account testAccount = new Account();
 testAccount.Name='Test Account' ;
 lstAccount.add(testAccount);
 Account testAccount1 = new Account();
 testAccount1.Name='Test Account11' ;
 lstAccount.add(testAccount1);

 insert  lstAccount;
 
 Test.startTest();
  Test.setCurrentPage(Page.YOUR_PAGE);
  ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(lstAccount);
  stdSetController.setSelected(lstAccount);
  YOUR_Extension ext = new YOUR_Extension(stdSetController);
 Test.stopTest();
 }
}



Please follow below salesforce Best Practice for Test Classes :-


1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible, @testSetup as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument, send no email ,
commit no data to database and flagged with testMethod keyword .
5. To deploy to production at least 75% code coverage is required
6. Test method and test classes are not counted as a part of code limit
7. System.debug statement are not counted as a part of apex code limit.8. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
  • Single Action -To verify that the the single record produces the correct an expected result .
  • Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
  • Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
  • Negative Testcase :-Not to add future date , Not to specify negative amount.
  • Restricted User :-Test whether a user with restricted access used in your code .
9. Test class should be annotated with @isTest .
10 . @isTest annotation with test method  is equivalent to testMethod keyword .
11. Test method should static and no void return type .

12. Test class and method default access is private ,no matter to add access specifier .
13. Classes with @isTest annotation can't be a interface or enum .
14. Test method code can't be invoked by non test request .
15. Stating with salesforce API 28.0 test method can not reside inside non test classes .
16. @Testvisible annotation to make visible private methods inside test classes.
17. Test method can't be used to test web-service call out . Please use call out mock .
18. You can't  send email from test method.

19.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
20. SeeAllData=true will not work for API 23 version eailer .
21. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
22. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
23. @testSetup to create test records once in a method  and use in every test method in the test class .
24. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
25. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
26. System.runAs will not enforce user permission or field level permission .
27. Every test to runAs count against the total number of DML issued in the process .



Please check below post to learn more about test classes.
 
 



Please let us know if this post will help you


Thanks
Amit Chaudhary

Thursday, 4 June 2015

Salesforce Testing Best Practice Guidelines | Unit Test Mechanism in Salesforce | Test Methods


Unit Test Mechanism in Salesforce

1) Single action

Test to verify that a single record produces the correct, expected result. So created the unit test data in your test class.

2) Bulk actions

Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only the single record case, but the bulk cases as well.

3) Restricted user

Test whether a user with restricted access to the sObjects used in your code sees the expected behavior. That is, whether they can run the code or receive error messages. Always use RunAs for to check user access on sObjects.

4) Positive behaviour

Test to verify that the expected behaviour occurs through every expected permutation, that is, that the user filled out everything correctly and did not go past the limits.

5) Negative behaviour

There are likely limits to your applications, such as not being able to add a future date, not being able to specify a negative amount, and so on. You must test for the negative case and verify that the error messages are correctly produced as well as for the positive, within the limits cases.

Test Methods

1) Apply testMethod or @isTest to methods

      • Demarcates a single self-contained test

public class MyClass 
{
  @isTest  
    private static void myTest() 
   {
      // code block
   }
}


2) Apply @isTest to classes

• Optional: test methods may also be contained in public classes
• Won’t count against the 2MB/org Apex code limit
– @isTest methods will not be shown in code coverage results
• The class must be marked as private
• Public methods can’t be called from outside the class


@isTest 
private class MyTestClass 
{
   @isTest private static void myTest() 
   {
 // code block
   }
}




Apex tests will not:

  1.  Commit changes to the database.
  2.  But SOQL queries will find records created during the test.
  3.  Perform callouts to external Web services.
  4.  Send outbound email.
  5.  Return results from SOSL searches.

Test Requirements in Production
  1. 75% of Apex statements must be executed (strive for 100% code coverage)
  2. All Apex triggers must be called. 
  3. All Apex tests must execute without throwing any uncaught exceptions or exceeding governors.


Step 1: Positive Path

Verify that when passed valid inputs, called code completes without throwing an exception.

Step 2: End state
  • Verify data-defined outcomes with assertions
  • System.assert()
  • System.assertEquals()
  • System.assertNotEquals()

Step 3: Negative Path

Verify that when passed invalid inputs, exceptions are properly handled

Step 4: Governors
  • Verify that code is bulk ready.
  • Pass up to 200 records.
  • Trade-off between test performance and effectiveness


Please let us know if this post will help you.


Thanks,
Amit Chaudhary


Thursday, 7 May 2015

Creating a sales invoice with financial force (no current company)


Problem :-  Creating a sales invoice with financial force

How to set Current Company by UI:-

Go to a non-setup page where you can see the left sidebar. The left sidebar near the top should show your 'current company'. 




If you have no 'current company',  a link saying 'Current Company not set' should appear there instead.
Click on the link and select a company from the list of companies that you have created.


Then create your invoice(s) as required

Test Class for Sales Invoice in Financial Force ( How to set current company by Code ) :-

@isTest 
private class salesInvoiceTestClass
{
 static testMethod void salesInvoiceTest() 
 {
 Group testGroup = new Group(Name='test group', Type='Queue');
 insert testGroup;
 QueuesObject testQueue ; 
 System.runAs(new User(Id=UserInfo.getUserId()))
 {
     List<queuesobject >  listQueue = new List<queuesobject >();
   queuesobject q1 = new queuesobject (queueid=testGroup.id, sobjecttype='Case'); 
   listQueue.add(q1);
   queuesobject q2 = new queuesobject (queueid=testGroup.id,                                                                 sobjecttype='c2g__codaAccountingCurrency__c'); 
   listQueue.add(q2);
   queuesobject q3 = new queuesobject (queueid=testGroup.id,                                                                 sobjecttype='c2g__codaPurchaseInvoice__c'); 
   listQueue.add(q3);
   queuesobject q4 = new queuesobject (queueid=testGroup.id, sobjecttype='c2g__codaCompany__c'); 
   listQueue.add(q4);
   queuesobject q5 = new queuesobject (queueid=testGroup.id, sobjecttype='c2g__codaYear__c'); 
   listQueue.add(q5);
   queuesobject q6 = new queuesobject (queueid=testGroup.id, sobjecttype='c2g__codaInvoice__c'); 
   listQueue.add(q6);
   insert  listQueue;

   GroupMember GroupMemberObj = new GroupMember();
   GroupMemberObj.GroupId = testGroup.id;
   GroupMemberObj.UserOrGroupId = UserInfo.getUserId();
   insert GroupMemberObj;
 }        

 c2g__codaCompany__c company = new c2g__codaCompany__c();
 company.Name = 'Test Record';
 company.JDE_Company_Code__c = '123';
 company.GLS_JE_Group_Number__c = '123' ;
 company.c2g__CashMatchingCurrencyMode__c = 'Test Account';
 company.c2g__YearEndMode__c = 'Test Code';
 company.c2g__ExternalId__c = 'ABCDE1234567876';
 company.c2g__LogoURL__c ='ww.XYZ.com';
 company.c2g__ECCountryCode__c = 'AE' ;
 company.c2g__VATRegistrationNumber__c = 'Test 222.222.222 TVA' ;
 company.c2g__Website__c = 'ww.xyz.com';
 company.c2g__Country__c ='US';
 company.ownerid = testGroup.Id;
 insert company;

 c2g__codaYear__c yr= new c2g__codaYear__c();
 yr.Name ='2015';
 yr.c2g__AutomaticPeriodList__c =  true;
 yr.c2g__OwnerCompany__c = company.id;
 yr.c2g__ExternalId__c = 'yzsd1234';
 yr.c2g__NumberOfPeriods__c =11;
 yr.c2g__StartDate__c =  system.today() - 10;
 yr.c2g__Status__c = 'Open';
 yr.c2g__PeriodCalculationBasis__c = '445';
 yr.c2g__YearEndMode__c = 'Full Accounting Code' ; 
 yr.c2g__UnitOfWork__c = 12;
 yr.ownerid = testGroup.Id;
 insert yr;

 c2g__codaPeriod__c prd = new c2g__codaPeriod__c();
 prd.Name ='Test2015';
 prd.c2g__ExternalId__c ='abdc12345';
 prd.c2g__StartDate__c = System.today()-10;
 prd.c2g__EndDate__c= System.today()+10;
 prd.c2g__OwnerCompany__c = company.id;
 prd.c2g__PeriodNumber__c ='123';
 prd.c2g__Description__c ='test Desc';
 prd.c2g__PeriodGroup__c = 'Q1';
 prd.c2g__PeriodNumber__c = '1';
 prd.c2g__YearName__c = yr.id;
 insert prd;

 c2g__codaUserCompany__c userCompany = new c2g__codaUserCompany__c();
 userCompany.c2g__Company__c =company.id;
 userCompany.c2g__User__c = userInfo.getUserId();
 userCompany.c2g__ExternalId__c = 'ABCDE1234567876';
 userCompany.c2g__UnitOfWork__c = 111 ;
 insert  userCompany;

 c2g__codaAccountingCurrency__c accCurrency = new c2g__codaAccountingCurrency__c();
 accCurrency.c2g__OwnerCompany__c = company.id;
 accCurrency.c2g__DecimalPlaces__c = 2;
 accCurrency.Name = 'AED';
 accCurrency.c2g__Dual__c = true ;
 accCurrency.ownerid = testGroup.Id;
 insert accCurrency;

 c2g__codaExchangeRate__c exchRate = new c2g__codaExchangeRate__c();
 exchRate.c2g__ExchangeRateCurrency__c = accCurrency.id;
 exchRate.c2g__OwnerCompany__c = company.id;
 exchRate.c2g__ExternalId__c ='12323232';
 exchRate.c2g__Rate__c =44.55;
 exchRate.c2g__StartDate__c = system.today()-10;
 exchRate.c2g__UnitOfWork__c =10;
 insert exchRate;       

 c2g__codaGeneralLedgerAccount__c GLAcc = new c2g__codaGeneralLedgerAccount__c();
 GLAcc.Name = 'Retained Earnings';
 GLAcc.c2g__BalanceSheet1__c ='Balance Sheet'; 
 GLAcc.Description__c ='test Desc';
 GLAcc.c2g__ExternalId__c ='testID';
 GLAcc.Account_Level__c = 'CAB';
 GLAcc.Business_Unit__c = 'RG';
 GLAcc.c2g__ReportingCode__c = '1234567543333';
 GLAcc.c2g__UnitOfWork__c =123;
 GLAcc.Reconciliation_Frequency__c ='Quarterly';
 GLAcc.c2g__TrialBalance1__c = 'Balance Sheet' ;
 GLAcc.c2g__Type__c = 'Balance Sheet' ;
 GLAcc.X10_Digit_GLA__c = false;
 insert GLAcc;

 Account acc= new Account();
 acc.Name='Test Account';
 acc.Account_Currency__c='USD';
 acc.CurrencyIsoCode='USD';
 acc.c2g__CODAAccountsPayableControl__c = GLAcc.Id;
 insert acc;

 c2g__codaInvoice__c testInvoice = new c2g__codaInvoice__c();
 testInvoice.CurrencyIsoCode = 'USD'
 testInvoice.c2g__InvoiceDate__c = date.today().addDays(-7)
 testInvoice.c2g__DueDate__c = date.today().addDays(-7)
 testInvoice.c2g__Account__c = acc.Id
 testInvoice.c2g__OwnerCompany__c = company.id
 testInvoice.ownerid = testGroup.Id
 insert testInvoice;            
 }  
}



Problem link :- https://developer.salesforce.com/forums/ForumsMain?id=906F000000092RnIAI