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
sylar2sylar2 

need urgent help on my first apex trigger

I'm new to apex and i have somehow managed to create a trigger in sandbox. It works fine.

The only issue is when i try to inbound change to production. Trigger deployment fails and covers only 0% of code.

 

I know the reason is i haven't created any test class for the trigger.

I don't know how to create one.

Please help.

 

following is my trigger.

 

trigger changeowner on Case (before insert,before update) {
    for(Case c : Trigger.new) {
        if (c.Status == 'Closed to Case Owner' ) {
            String createId = c.CreatedById;
            c.OwnerId = createId.subString(0, 15);
        }
    }
}

 

Best Answer chosen by Admin (Salesforce Developers) 
hwelchhwelch

You should go through the Apex Developer's Guide but for now your answer is below.  Remeber to create an apex class using the "Test Class" template.  Also you can optimize your trigger by removing "String createId = c.CreatedById; c.OwnerId = createId.subString(0, 15);" with "c.OwnerId = c.CreatedById".

 

 

@isTest
private class changeownertest {

    static testMethod void myUnitTest() {
        Case c = new Case();
        c.status = 'Closed to Case Owner';
        c.Origin = 'Phone';

        // make sure your assign any other required fields
        insert c;
        System.assertNotEquals(c.id, null);
    }
}

All Answers

hwelchhwelch

You should go through the Apex Developer's Guide but for now your answer is below.  Remeber to create an apex class using the "Test Class" template.  Also you can optimize your trigger by removing "String createId = c.CreatedById; c.OwnerId = createId.subString(0, 15);" with "c.OwnerId = c.CreatedById".

 

 

@isTest
private class changeownertest {

    static testMethod void myUnitTest() {
        Case c = new Case();
        c.status = 'Closed to Case Owner';
        c.Origin = 'Phone';

        // make sure your assign any other required fields
        insert c;
        System.assertNotEquals(c.id, null);
    }
}

This was selected as the best answer
sylar2sylar2
Test Failures 

The test fails and give following error.

I have also put the debug log.

changeownertest
Method Name
Total Time (ms)
Message
Stack Trace
changeownertest.myUnitTest65.0System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, changeowner: data changed by trigger for field Owner ID: owner cannot be blank: []Class.changeownertest.myUnitTest: line 8, column 9 External entry point
<script type="text/javascript">// function twistSection(twisty, sectionId) { var parentDiv = twisty; while (parentDiv.tagName != 'DIV') { parentDiv = parentDiv.parentNode; } var div = parentDiv.nextSibling; var elemWasOn = false; if (div.style.display != 'none') { div.style.display = 'none'; twisty.className ='showListButton'; twisty.alt = twisty.title = 'Show Section - '+twisty.name; elemWasOn = true; } else { div.style.display = 'block'; twisty.className = 'hideListButton'; twisty.alt = twisty.title = 'Hide Section - '+twisty.name; } return !elemWasOn; } var registeredSections = new Array(); function registerTwistableSection(headerId, mainTableId) { var obj = new Object(); obj.headerId = headerId; obj.mainTableId = mainTableId; registeredSections[registeredSections.length] = obj; } function twistAllSections(on) { for (var i = 0; i < registeredSections.length; i++) { var obj = registeredSections[i]; var img; img = document.getElementById('img_' + obj.headerId); if (on && 'showListButton' == img.className) { twistSection(img, obj.headerId, obj.mainTableId); } else if (!on && 'hideListButton' == img.className) { twistSection(img, obj.headerId, obj.mainTableId); } } } function toggleSection(headerId, on){ var sectionHead = document.getElementById('head_'+headerId+'_page_template_testResults_j_id35'); var body = sectionHead.nextSibling; var disp = on ? 'block' : 'none'; sectionHead.style.display = disp; body.style.display = disp; } function registerTwistableSections_page_template_testResults_j_id35() { registerTwistableSection('page_template_testResults_j_id35_j_id36', 'page_template_testResults_j_id35'); registerTwistableSection('page_template_testResults_j_id35_j_id48', 'page_template_testResults_j_id35'); } registerTwistableSections_page_template_testResults_j_id35(); // </script>
Code Coverage 
Hide Section - Trigger Code CoverageTrigger Code Coverage
Trigger Name
Coverage %
changeowner100
Debug Log 

21.0 APEX_CODE,FINE;APEX_PROFILING,FINE;DB,INFO;VALIDATION,INFO;WORKFLOW,FINEST
13:21:19.151|EXECUTION_STARTED
13:21:19.151|CODE_UNIT_STARTED|[EXTERNAL]|01pS00000001hiI|changeownertest.myUnitTest
13:21:19.151|METHOD_ENTRY|[2]|01pS00000001hiI|changeownertest.changeownertest()
13:21:19.151|METHOD_EXIT|[2]|changeownertest
13:21:19.151|DML_BEGIN|[8]|Op:Insert|Type:Case|Rows:1
13:21:19.181|CODE_UNIT_STARTED|[EXTERNAL]|01qS00000000Wi9|changeowner on Case trigger event BeforeInsert for [new]
13:21:19.488|CUMULATIVE_LIMIT_USAGE
13:21:19.488|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 0 out of 100
Number of query rows: 0 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 1 out of 150
Number of DML rows: 1 out of 10000
Number of script statements: 5 out of 200000
Maximum heap size: 0 out of 3000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10

13:21:19.488|TOTAL_EMAIL_RECIPIENTS_QUEUED|0
13:21:19.488|CUMULATIVE_LIMIT_USAGE_END

13:21:19.182|CODE_UNIT_FINISHED|changeowner on Case trigger event BeforeInsert for [new]
13:21:19.183|DML_END|[8]
13:21:19.183|EXCEPTION_THROWN|[8]|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, changeowner: data changed by trigger for field Owner ID: owner cannot be blank: []
13:21:19.185|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, changeowner: data changed by trigger for field Owner ID: owner cannot be blank: []

Class.changeownertest.myUnitTest: line 8, column 9
External entry point
13:21:19.492|CUMULATIVE_LIMIT_USAGE
13:21:19.492|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 0 out of 100
Number of query rows: 0 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 1 out of 150
Number of DML rows: 1 out of 10000
Number of script statements: 4 out of 200000
Maximum heap size: 0 out of 3000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10

13:21:19.492|TOTAL_EMAIL_RECIPIENTS_QUEUED|0
13:21:19.492|CUMULATIVE_LIMIT_USAGE_END

13:21:19.186|CODE_UNIT_FINISHED|changeownertest.myUnitTest
13:21:19.186|EXECUTION_FINISHED
13:21:19.669|CUMULATIVE_PROFILING_BEGIN
13:21:19.669|CUMULATIVE_PROFILING|No profiling information for SOQL operations
13:21:19.669|CUMULATIVE_PROFILING|No profiling information for SOSL operations
13:21:19.669|CUMULATIVE_PROFILING|No profiling information for DML operations
13:21:19.669|CUMULATIVE_PROFILING|No profiling information for method invocations
13:21:19.669|CUMULATIVE_PROFILING_END

hwelchhwelch

oh right .. this is a before insert trigger so createdbyid is null.  You may want to branch out in the trigger to handle before insert and beforeupdate seperately.  The beforeupdate can handle assigning owner = createdby and the beforeinsert could be the current user.  Though typically when you create a new record you become the owner of that record unless you have assignment rules kicking off?

sylar2sylar2

 

 

 

If i remove before insert, test is successful but code coverage becomes 0

 

how do i branch out the before insert?

it would be great if you can provide me the code,

 

hwelchhwelch

If you removed the "before insert" from your trigger then code coverage is zero because there's no update in the test class and so your trigger isn't being fired anymore.  You need to append the following line to the test class to fire off your trigger.

 

update c;

 

Nik'sNik's

If you will move your code in Class with Static Method you can easily done woth code coverage. When you try with Change Set it also fine that code coverage of all apllication should be 75%.

sylar2sylar2

Apex Developer's Guide rocks... its done.. thanks everyone...