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
JonSimmonsJonSimmons 

Unit Test Example

 
I am working on writing a set of triggers with success but I'm struggling with the Unit Tests.   My trigger code works perfectly but I can't get salesforce to accept my unit tests, it seems like the more unit tests I create the lower my unit test coverage gets.
 
As I understand it any method marked with the TestMethod modifier is defined as a test method and therefore should not be used to calculate the percentage of coverage on the remaining code.  I am running the tests at Salesforce in my Dev Org and I can see which lines of code are not covered and which are covered, as I mark my code with the testmethod modifier I see the uncovered lines go away, but so does my percentage of covered code.
 
I believe that the problem is that I'm not calling my methods directly, but rather creating/updating/deleting records that should fire triggers that call my methods.  As I understand it, this should be sufficient as the code that the trigger calls should be included in the test, but this isnt' what I'm seeing happening.  Conversely, if I do call my methods directly I get the exact same results, salesforce reports that I'm not testig the methods that I am calling and then assertion testing.
 
Everything I do seems to make the situation worse so I'm at a loss as to how to create unit tests at all.
 
Can someone take a look at the code below and give me an example of a unit test to cover this portion of my code?  That should get me moving in the right direction for the remainder.
 
 
 
The trigger should fire upon insert of a custom object, the result should be the insert of a new ContactShare object with userid and contactid from the custom object.   The code works flawlessly, I just can't seem to make the UnitTests work.
 
Many Thanks
Jon
 
 
 
 

trigger Sharing_on_Additional_Contact_Owner on Additional_Contact_Owner__c (before delete, after insert, after update)

{

   if (Trigger.isInsert) //we must be inserting

   {

      Classes_and_Unit_Tests.InsertContactShare(Trigger.new[0].Contact_Name__c, Trigger.new[0].Additional_Contact_Owner_Name__c);

   }

}

 
 
 

public class Classes_and_Unit_Tests

{

   public static void InsertContactShare(id newContactId, id newOwnerId)

   {

   // given an Additional_Contact_Owner__c record, insert a new contactshare record providing Contact access to a User

      try

      {

            //instantiate the object

            ContactShare theShare = new ContactShare();

            //update the object

            theShare.ContactAccessLevel = 'Edit';

            theShare.ContactId = newContactId;

            theShare.UserOrGroupId = newOwnerId;

            //insert it into salesforce

            insert (theShare);

      }

      catch (Exception e)

      {

      //do nothing for now

      }

}  //end insertcontactshare method

 

} //end class

 
 
 
 
 
BritishBoyinDCBritishBoyinDC
That's not an easy test script, because for it to work across instances, you need to create the contact and then do a SOQL for a user which will work across instances.

But you could add something like this into the class

static testMethod void TestSharing_on_Additional_Contact_Owner() {

Contact c = new Contact (
LastName = 'Test Contact');
insert c;

String aUserName = 'myname@mydomain.com%';
// the % wild card will enable you to use this across instances, assuming you are in a sandbox - if you in a dev environment, you would need to create a user for this part

User user = [select id from User where UserName like : aUserName LIMIT 1];

Additional_Contact_Owner__c aco = new Additional_Contact_Owner__c (
Contact_Name__c = c.id,
Additional_Contact_Owner_Name__c = user.id);
insert aco;

// you should then do some system asserts to check the record was created by selecting for the aco record that was created, and that the trigger created new record
}
JonSimmonsJonSimmons
What you describe is essentially what I am doing to test.
 
Running across instances is not my concern at the moment, if I can get the unit tests to be accepted I can deal with adjusting for the production instance. 
My real problem is that no matter what I test or how I test it salesforce.com tells me I'm not testing.  I'm apparently doing something wrong but the documentation for unit testing is not all that complete or even slightly usefull.
 
My unit tests consist of about 3x more code then the code I am testing.  In order to test for the creation of one records I must create 4 others.
 
Create Account (Account is required for Contact)
Create Contact
Create User
Create Custom Object, specifying created ContactId and created UserId
  Trigger should fire, using ContactId and UserId to create new ContactShare  (This works perfectly)
Test to verify that ContactShare has been created
 
The problem is that Salesforce thinks that my Create_ContactShare code is not being tested, though it should be since the Trigger is calling it, I know that because the trigger works and creates the ContactShare object as expected.
 
 
 
I just spent the last 3 hours completely re-writing all of my unit test code, debugging and getting salesforce to accept that I am testing over 75% of the code.  So everything is perfect on my Dev Site, the Trigger works and the Unit Test code works without any errors and is accepted.
 
I take the exact same code and transfer it to my production org (after adjusting for the different instance) and it fails to upload, claiming that I have 0% (ZERO PERCENT!!!!) unit test coverage.   The same code is completely useless in an identical production environment.  WTF?
 
Can anyone tell me what I am doing wrong here?
 
 


Message Edited by JonSimmons on 11-07-2008 05:20 PM
BritishBoyinDCBritishBoyinDC
The zero percent error is caused if the test fails during deployment - if the test can't complete, then none of the code is considered tested. I have found through frustrating experience that a test may succeed in dev because there is existing secondary data that allows it to complete which isn't there in a different environment (e.g. a required default value for a dependent trigger on the account.)

So I suspect it is an issue with the test failing when it is being deployed - what I might suggest is creating the trigger and class directly in a different dev/clean sandbox environment, run the tests and see if it fails - if so, you should get an idea where the problem is.
JonSimmonsJonSimmons

 

Yeah, frustrating is a word for it, it would be super nice if salesforce actually provided some usefull error messages once in a while.

 

You are correct about the zero percent being because the code failed to save, the problem is figuring out why it failed to save since Salesforce isn't providing any usefull error messages.  

What is frustrating me at the moment is that the unit test code (while testing from within eclipse) appears to prepare to call the trigger but doesn't actually call any of the trigger code as none of my system.debug messages show up in the log.  It does appear to call code that the trigger should be calling but that code is failing for no apparent reason.

 

I continue to plod along

 

Thanks

Jon

 

 

JonSimmonsJonSimmons
Are there any good reasons why my unit test would claim it's about to call my trigger and then simply not do it?   There are a bunch of system.debug calls within my trigger (none of which show up below) and an assertion test afterwards that show the trigger isn't being called.  What's up with that?
 
 
 
20081108040731.026:Class.HarvestClassesandUnitTests.testDeleteContactShare: line 216, column 1: About to call the AfterInsert Trigger
20081108040731.026:Class.HarvestClassesandUnitTests.testDeleteContactShare: line 218, column 9: Insert: SOBJECT:Additional_Contact_Owner__c
*** Beginning Sharing_on_Additional_Contact_Owner on Additional_Contact_Owner trigger event AfterInsert for a0960000004JsDU

Cumulative resource usage:
Resource usage for namespace: (default)
Number of SOQL queries: 0 out of 100
Number of query rows: 0 out of 500
Number of SOSL queries: 0 out of 20
Number of DML statements: 3 out of 100
Number of DML rows: 3 out of 500
Number of script statements: 14 out of 200000
Maximum heap size: 0 out of 500000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 10
Number of record type describes: 0 out of 10
Number of child relationships describes: 0 out of 10
Number of picklist describes: 0 out of 10
Number of future calls: 0 out of 10
Number of find similar calls: 0 out of 10
Number of System.runAs() invocations: 0 out of 20
Total email recipients queued to be sent : 0
*** Ending Sharing_on_Additional_Contact_Owner on Additional_Contact_Owner trigger event AfterInsert for a0960000004JsDU
20081108040731.026:Class.HarvestClassesandUnitTests.testDeleteContactShare: line 218, column 9:     DML Operation executed in 29 ms
20081108040731.026:Class.HarvestClassesandUnitTests.testDeleteContactShare: line 219, column 1: After the AfterInsert Trigger