Is my test coverage up to snuff?Test Apex Class , failing - Need helpTest Class failregd Test classUnit Test is Providing 0% Coverage for Apex Trigger“Required fields are missing: [ProfileId]: [ProfileId]” when running Apex Class Test for ChatterAnswersAuthProviderRegTestTest Class with Account TransferError on Test Class - System.QueryException: List has no rows for assignment to SObjectCode Coverage to Test Custom Object Public ListSOQL returning org data in test class. Not using isTest(SeeAllData=true)I have a trigger with handler, and done test class as below,please let me know any further modifications required
Is random forest for regression a 'true' regression?
Why are lawsuits between the President and Congress not automatically sent to the Supreme Court
Why does SSL Labs now consider CBC suites weak?
How to continually let my readers know what time it is in my story, in an organic way?
The difference between きわめて and いたって
When did game consoles begin including FPUs?
Is there any good reason to write "it is easy to see"?
Why did the metro bus stop at each railway crossing, despite no warning indicating a train was coming?
With today's technology, could iron be smelted at La Rinconada?
How to describe a building set which is like LEGO without using the "LEGO" word?
Assembly writer vs compiler
Will British Airways compensate if my entertainment screen was defective for an entire flight?
Looking for source for a "yield space" rule my 3.5 group uses
What color to choose as "danger" if the main color of my app is red
Network latencies between opposite ends of the Earth
Should I communicate in my applications that I'm unemployed out of choice rather than because nobody will have me?
UUID type for NEWID()
Does addError() work outside of triggers?
How could it be that 80% of townspeople were farmers during the Edo period in Japan?
Does it matter what way the tires go if no directional arrow?
Is my test coverage up to snuff?
Why were the bells ignored in S8E5?
God-Pharaoh's Statue and Finale Of Promise
Can my American children re-enter the USA by International flight with a passport card? Being that their passport book has expired
Is my test coverage up to snuff?
Test Apex Class , failing - Need helpTest Class failregd Test classUnit Test is Providing 0% Coverage for Apex Trigger“Required fields are missing: [ProfileId]: [ProfileId]” when running Apex Class Test for ChatterAnswersAuthProviderRegTestTest Class with Account TransferError on Test Class - System.QueryException: List has no rows for assignment to SObjectCode Coverage to Test Custom Object Public ListSOQL returning org data in test class. Not using isTest(SeeAllData=true)I have a trigger with handler, and done test class as below,please let me know any further modifications required
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I've got a theoretical, rather than a practical, question today. I just wrote the trigger and test class below. I'd love to get feedback on such questions as:
1. Do I test sufficient cases? (It gets 100% coverage, but that's not the same thing.)
2. Any comments on my style or method?
Trigger:
trigger OpportunityBeforeDelete on Opportunity (before delete)
String profileName = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId()].Name;
for(Opportunity opp: trigger.old)
if (opp.Receivable__c == true && profileName != 'System Administrator')
opp.adderror('Receivable opportunities should not be deleted. See wiki: https://sites.google.com/a/sparkprogram.org/spark-interconnected-data-systems-wiki/finance/receivable-opportunities Receivable opportunities can only be deleted by a system administrator.');
And this test class:
@isTest
public class testOpportunityBeforeDelete
//test class for trigger OpportunityBeforeDelete
@isTest
public static void myTestMethod()
//insert a User that is not sysadmin
Profile p = [SELECT Id FROM Profile WHERE Name='Spark Exec'];
User standardu = new User(Alias = 'standt', Email='standarduser@sparkprogram.org',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@sparkprogram.org');
insert standardu;
system.runAs(standardu)
//Insert an account
Account newaccount = new Account (
Name = 'Account');
insert newaccount;
//Insert an opportunity
Opportunity newopp = new Opportunity (
Name = 'Test to be Receivable',
AccountId = newaccount.Id,
Amount = 10000,
StageName = 'Receivable',
Receivable__c = true,
CloseDate = system.today()
);
insert newopp;
// Perform test
Test.startTest();
try
delete newopp;
catch (DMLException e)
// expected - could assert the message here
Database.DeleteResult result = Database.delete(newopp, false);
//Test.stopTest();
System.assert(!result.isSuccess());
System.assert(result.getErrors().size() > 0);
System.assertEquals('Receivable opportunities should not be deleted. See wiki: https://sites.google.com/a/sparkprogram.org/spark-interconnected-data-systems-wiki/finance/receivable-opportunities Receivable opportunities can only be deleted by a system administrator.',
result.getErrors()[0].getMessage());
apex trigger unit-test code-coverage
add a comment |
I've got a theoretical, rather than a practical, question today. I just wrote the trigger and test class below. I'd love to get feedback on such questions as:
1. Do I test sufficient cases? (It gets 100% coverage, but that's not the same thing.)
2. Any comments on my style or method?
Trigger:
trigger OpportunityBeforeDelete on Opportunity (before delete)
String profileName = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId()].Name;
for(Opportunity opp: trigger.old)
if (opp.Receivable__c == true && profileName != 'System Administrator')
opp.adderror('Receivable opportunities should not be deleted. See wiki: https://sites.google.com/a/sparkprogram.org/spark-interconnected-data-systems-wiki/finance/receivable-opportunities Receivable opportunities can only be deleted by a system administrator.');
And this test class:
@isTest
public class testOpportunityBeforeDelete
//test class for trigger OpportunityBeforeDelete
@isTest
public static void myTestMethod()
//insert a User that is not sysadmin
Profile p = [SELECT Id FROM Profile WHERE Name='Spark Exec'];
User standardu = new User(Alias = 'standt', Email='standarduser@sparkprogram.org',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@sparkprogram.org');
insert standardu;
system.runAs(standardu)
//Insert an account
Account newaccount = new Account (
Name = 'Account');
insert newaccount;
//Insert an opportunity
Opportunity newopp = new Opportunity (
Name = 'Test to be Receivable',
AccountId = newaccount.Id,
Amount = 10000,
StageName = 'Receivable',
Receivable__c = true,
CloseDate = system.today()
);
insert newopp;
// Perform test
Test.startTest();
try
delete newopp;
catch (DMLException e)
// expected - could assert the message here
Database.DeleteResult result = Database.delete(newopp, false);
//Test.stopTest();
System.assert(!result.isSuccess());
System.assert(result.getErrors().size() > 0);
System.assertEquals('Receivable opportunities should not be deleted. See wiki: https://sites.google.com/a/sparkprogram.org/spark-interconnected-data-systems-wiki/finance/receivable-opportunities Receivable opportunities can only be deleted by a system administrator.',
result.getErrors()[0].getMessage());
apex trigger unit-test code-coverage
2
Per this meta post, we would advise you to ask your question on CRSE for a more in-depth code review. Do, however, feel free to post in our Salesforce Meta so that we can be made aware of it. Thanks!
– sfdcfox
2 hours ago
add a comment |
I've got a theoretical, rather than a practical, question today. I just wrote the trigger and test class below. I'd love to get feedback on such questions as:
1. Do I test sufficient cases? (It gets 100% coverage, but that's not the same thing.)
2. Any comments on my style or method?
Trigger:
trigger OpportunityBeforeDelete on Opportunity (before delete)
String profileName = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId()].Name;
for(Opportunity opp: trigger.old)
if (opp.Receivable__c == true && profileName != 'System Administrator')
opp.adderror('Receivable opportunities should not be deleted. See wiki: https://sites.google.com/a/sparkprogram.org/spark-interconnected-data-systems-wiki/finance/receivable-opportunities Receivable opportunities can only be deleted by a system administrator.');
And this test class:
@isTest
public class testOpportunityBeforeDelete
//test class for trigger OpportunityBeforeDelete
@isTest
public static void myTestMethod()
//insert a User that is not sysadmin
Profile p = [SELECT Id FROM Profile WHERE Name='Spark Exec'];
User standardu = new User(Alias = 'standt', Email='standarduser@sparkprogram.org',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@sparkprogram.org');
insert standardu;
system.runAs(standardu)
//Insert an account
Account newaccount = new Account (
Name = 'Account');
insert newaccount;
//Insert an opportunity
Opportunity newopp = new Opportunity (
Name = 'Test to be Receivable',
AccountId = newaccount.Id,
Amount = 10000,
StageName = 'Receivable',
Receivable__c = true,
CloseDate = system.today()
);
insert newopp;
// Perform test
Test.startTest();
try
delete newopp;
catch (DMLException e)
// expected - could assert the message here
Database.DeleteResult result = Database.delete(newopp, false);
//Test.stopTest();
System.assert(!result.isSuccess());
System.assert(result.getErrors().size() > 0);
System.assertEquals('Receivable opportunities should not be deleted. See wiki: https://sites.google.com/a/sparkprogram.org/spark-interconnected-data-systems-wiki/finance/receivable-opportunities Receivable opportunities can only be deleted by a system administrator.',
result.getErrors()[0].getMessage());
apex trigger unit-test code-coverage
I've got a theoretical, rather than a practical, question today. I just wrote the trigger and test class below. I'd love to get feedback on such questions as:
1. Do I test sufficient cases? (It gets 100% coverage, but that's not the same thing.)
2. Any comments on my style or method?
Trigger:
trigger OpportunityBeforeDelete on Opportunity (before delete)
String profileName = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId()].Name;
for(Opportunity opp: trigger.old)
if (opp.Receivable__c == true && profileName != 'System Administrator')
opp.adderror('Receivable opportunities should not be deleted. See wiki: https://sites.google.com/a/sparkprogram.org/spark-interconnected-data-systems-wiki/finance/receivable-opportunities Receivable opportunities can only be deleted by a system administrator.');
And this test class:
@isTest
public class testOpportunityBeforeDelete
//test class for trigger OpportunityBeforeDelete
@isTest
public static void myTestMethod()
//insert a User that is not sysadmin
Profile p = [SELECT Id FROM Profile WHERE Name='Spark Exec'];
User standardu = new User(Alias = 'standt', Email='standarduser@sparkprogram.org',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@sparkprogram.org');
insert standardu;
system.runAs(standardu)
//Insert an account
Account newaccount = new Account (
Name = 'Account');
insert newaccount;
//Insert an opportunity
Opportunity newopp = new Opportunity (
Name = 'Test to be Receivable',
AccountId = newaccount.Id,
Amount = 10000,
StageName = 'Receivable',
Receivable__c = true,
CloseDate = system.today()
);
insert newopp;
// Perform test
Test.startTest();
try
delete newopp;
catch (DMLException e)
// expected - could assert the message here
Database.DeleteResult result = Database.delete(newopp, false);
//Test.stopTest();
System.assert(!result.isSuccess());
System.assert(result.getErrors().size() > 0);
System.assertEquals('Receivable opportunities should not be deleted. See wiki: https://sites.google.com/a/sparkprogram.org/spark-interconnected-data-systems-wiki/finance/receivable-opportunities Receivable opportunities can only be deleted by a system administrator.',
result.getErrors()[0].getMessage());
apex trigger unit-test code-coverage
apex trigger unit-test code-coverage
edited 2 hours ago
sfdcfox
270k13217467
270k13217467
asked 2 hours ago
Michael KolodnerMichael Kolodner
897
897
2
Per this meta post, we would advise you to ask your question on CRSE for a more in-depth code review. Do, however, feel free to post in our Salesforce Meta so that we can be made aware of it. Thanks!
– sfdcfox
2 hours ago
add a comment |
2
Per this meta post, we would advise you to ask your question on CRSE for a more in-depth code review. Do, however, feel free to post in our Salesforce Meta so that we can be made aware of it. Thanks!
– sfdcfox
2 hours ago
2
2
Per this meta post, we would advise you to ask your question on CRSE for a more in-depth code review. Do, however, feel free to post in our Salesforce Meta so that we can be made aware of it. Thanks!
– sfdcfox
2 hours ago
Per this meta post, we would advise you to ask your question on CRSE for a more in-depth code review. Do, however, feel free to post in our Salesforce Meta so that we can be made aware of it. Thanks!
– sfdcfox
2 hours ago
add a comment |
3 Answers
3
active
oldest
votes
I wanted to point out a major hole in your logic, you probably will want to correct the pattern you used above.
Here's your original code with a note
try
delete newopp;
//NOTE: WHAT HAPPENS HERE IF THE EXCEPTION IS NOT THROWN?
catch (DMLException e)
// expected - could assert the message here
If the error is thrown, your test has to fail... but you're not making it fail. So, with a small change, your test will correctly fail if your exception is not thrown
try
delete newopp;
System.assert(false);
catch (DMLException e)
System.assert(true); //Not Needed, I just like doing it anyway
// Assert everything else you need here
With that small change, you'll be validating correctly that an exception must be thrown.
1
This can't be a validation rule because you can't prevent deletion with a VR, only an edit. (Unless you know something about VRs that I don't know.)
– Michael Kolodner
2 hours ago
I'll be damned, I missed that this was a deletion. Anyway, my tip is still valid
– Sebastian Kessel
2 hours ago
Updated my answer based on your feedback.
– Sebastian Kessel
2 hours ago
add a comment |
No, your coverage is not adequate, even if you hit every line. You should look up and read about Cyclomatic Complexity, and aim to cover every major branch. Specifically, you do not have a test method which verifies a System Administrator is exempted from the rule. Similarly, you should verify that all users are still able to delete records where Receivable__c == false.
In every unit test, you should have unconditional assertions which verify the behavior you expect. Typically to verify that a validation is thrown, mine looks like:
DmlException expectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
expectedException = dmx;
Test.stopTest();
system.assertNotEquals(null, expectedException, 'The operation should fail');
// optionally run a query and assert on those results as well
The converse:
DmlException unexpectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
unexpectedException = dmx;
Test.stopTest();
system.assertEquals(null, unexpectedException, 'The operation should succeed');
// optionally run a query and assert on those results as well
1
Point taken that I need to test for a sysadmin being exempted. But it's not possible to prevent a delete with a validation rule, that's why I have to write a trigger.
– Michael Kolodner
2 hours ago
Ah good point, I did not look at the trigger event.
– Adrian Larson♦
2 hours ago
add a comment |
Another perspective on testing.
IMHO tests should confirm the planned behavior of the software: i.e. confirming customer visible/required behavior is priority #1. That is what your customer is paying for and wants to work. Start from those requirements when you write your tests, not from the code you have written to implement those requirements.
Sometimes you might write some tests that cover the building blocks that help you deliver that required behavior but that is essentially arbitrary implementation detail so is much less important.
Focussing on code coverage often leads people in a bad direction, where they have great code coverage but no assurance that the requirements are being met.
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "459"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f262404%2fis-my-test-coverage-up-to-snuff%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
I wanted to point out a major hole in your logic, you probably will want to correct the pattern you used above.
Here's your original code with a note
try
delete newopp;
//NOTE: WHAT HAPPENS HERE IF THE EXCEPTION IS NOT THROWN?
catch (DMLException e)
// expected - could assert the message here
If the error is thrown, your test has to fail... but you're not making it fail. So, with a small change, your test will correctly fail if your exception is not thrown
try
delete newopp;
System.assert(false);
catch (DMLException e)
System.assert(true); //Not Needed, I just like doing it anyway
// Assert everything else you need here
With that small change, you'll be validating correctly that an exception must be thrown.
1
This can't be a validation rule because you can't prevent deletion with a VR, only an edit. (Unless you know something about VRs that I don't know.)
– Michael Kolodner
2 hours ago
I'll be damned, I missed that this was a deletion. Anyway, my tip is still valid
– Sebastian Kessel
2 hours ago
Updated my answer based on your feedback.
– Sebastian Kessel
2 hours ago
add a comment |
I wanted to point out a major hole in your logic, you probably will want to correct the pattern you used above.
Here's your original code with a note
try
delete newopp;
//NOTE: WHAT HAPPENS HERE IF THE EXCEPTION IS NOT THROWN?
catch (DMLException e)
// expected - could assert the message here
If the error is thrown, your test has to fail... but you're not making it fail. So, with a small change, your test will correctly fail if your exception is not thrown
try
delete newopp;
System.assert(false);
catch (DMLException e)
System.assert(true); //Not Needed, I just like doing it anyway
// Assert everything else you need here
With that small change, you'll be validating correctly that an exception must be thrown.
1
This can't be a validation rule because you can't prevent deletion with a VR, only an edit. (Unless you know something about VRs that I don't know.)
– Michael Kolodner
2 hours ago
I'll be damned, I missed that this was a deletion. Anyway, my tip is still valid
– Sebastian Kessel
2 hours ago
Updated my answer based on your feedback.
– Sebastian Kessel
2 hours ago
add a comment |
I wanted to point out a major hole in your logic, you probably will want to correct the pattern you used above.
Here's your original code with a note
try
delete newopp;
//NOTE: WHAT HAPPENS HERE IF THE EXCEPTION IS NOT THROWN?
catch (DMLException e)
// expected - could assert the message here
If the error is thrown, your test has to fail... but you're not making it fail. So, with a small change, your test will correctly fail if your exception is not thrown
try
delete newopp;
System.assert(false);
catch (DMLException e)
System.assert(true); //Not Needed, I just like doing it anyway
// Assert everything else you need here
With that small change, you'll be validating correctly that an exception must be thrown.
I wanted to point out a major hole in your logic, you probably will want to correct the pattern you used above.
Here's your original code with a note
try
delete newopp;
//NOTE: WHAT HAPPENS HERE IF THE EXCEPTION IS NOT THROWN?
catch (DMLException e)
// expected - could assert the message here
If the error is thrown, your test has to fail... but you're not making it fail. So, with a small change, your test will correctly fail if your exception is not thrown
try
delete newopp;
System.assert(false);
catch (DMLException e)
System.assert(true); //Not Needed, I just like doing it anyway
// Assert everything else you need here
With that small change, you'll be validating correctly that an exception must be thrown.
edited 2 hours ago
answered 2 hours ago
Sebastian KesselSebastian Kessel
9,34262239
9,34262239
1
This can't be a validation rule because you can't prevent deletion with a VR, only an edit. (Unless you know something about VRs that I don't know.)
– Michael Kolodner
2 hours ago
I'll be damned, I missed that this was a deletion. Anyway, my tip is still valid
– Sebastian Kessel
2 hours ago
Updated my answer based on your feedback.
– Sebastian Kessel
2 hours ago
add a comment |
1
This can't be a validation rule because you can't prevent deletion with a VR, only an edit. (Unless you know something about VRs that I don't know.)
– Michael Kolodner
2 hours ago
I'll be damned, I missed that this was a deletion. Anyway, my tip is still valid
– Sebastian Kessel
2 hours ago
Updated my answer based on your feedback.
– Sebastian Kessel
2 hours ago
1
1
This can't be a validation rule because you can't prevent deletion with a VR, only an edit. (Unless you know something about VRs that I don't know.)
– Michael Kolodner
2 hours ago
This can't be a validation rule because you can't prevent deletion with a VR, only an edit. (Unless you know something about VRs that I don't know.)
– Michael Kolodner
2 hours ago
I'll be damned, I missed that this was a deletion. Anyway, my tip is still valid
– Sebastian Kessel
2 hours ago
I'll be damned, I missed that this was a deletion. Anyway, my tip is still valid
– Sebastian Kessel
2 hours ago
Updated my answer based on your feedback.
– Sebastian Kessel
2 hours ago
Updated my answer based on your feedback.
– Sebastian Kessel
2 hours ago
add a comment |
No, your coverage is not adequate, even if you hit every line. You should look up and read about Cyclomatic Complexity, and aim to cover every major branch. Specifically, you do not have a test method which verifies a System Administrator is exempted from the rule. Similarly, you should verify that all users are still able to delete records where Receivable__c == false.
In every unit test, you should have unconditional assertions which verify the behavior you expect. Typically to verify that a validation is thrown, mine looks like:
DmlException expectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
expectedException = dmx;
Test.stopTest();
system.assertNotEquals(null, expectedException, 'The operation should fail');
// optionally run a query and assert on those results as well
The converse:
DmlException unexpectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
unexpectedException = dmx;
Test.stopTest();
system.assertEquals(null, unexpectedException, 'The operation should succeed');
// optionally run a query and assert on those results as well
1
Point taken that I need to test for a sysadmin being exempted. But it's not possible to prevent a delete with a validation rule, that's why I have to write a trigger.
– Michael Kolodner
2 hours ago
Ah good point, I did not look at the trigger event.
– Adrian Larson♦
2 hours ago
add a comment |
No, your coverage is not adequate, even if you hit every line. You should look up and read about Cyclomatic Complexity, and aim to cover every major branch. Specifically, you do not have a test method which verifies a System Administrator is exempted from the rule. Similarly, you should verify that all users are still able to delete records where Receivable__c == false.
In every unit test, you should have unconditional assertions which verify the behavior you expect. Typically to verify that a validation is thrown, mine looks like:
DmlException expectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
expectedException = dmx;
Test.stopTest();
system.assertNotEquals(null, expectedException, 'The operation should fail');
// optionally run a query and assert on those results as well
The converse:
DmlException unexpectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
unexpectedException = dmx;
Test.stopTest();
system.assertEquals(null, unexpectedException, 'The operation should succeed');
// optionally run a query and assert on those results as well
1
Point taken that I need to test for a sysadmin being exempted. But it's not possible to prevent a delete with a validation rule, that's why I have to write a trigger.
– Michael Kolodner
2 hours ago
Ah good point, I did not look at the trigger event.
– Adrian Larson♦
2 hours ago
add a comment |
No, your coverage is not adequate, even if you hit every line. You should look up and read about Cyclomatic Complexity, and aim to cover every major branch. Specifically, you do not have a test method which verifies a System Administrator is exempted from the rule. Similarly, you should verify that all users are still able to delete records where Receivable__c == false.
In every unit test, you should have unconditional assertions which verify the behavior you expect. Typically to verify that a validation is thrown, mine looks like:
DmlException expectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
expectedException = dmx;
Test.stopTest();
system.assertNotEquals(null, expectedException, 'The operation should fail');
// optionally run a query and assert on those results as well
The converse:
DmlException unexpectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
unexpectedException = dmx;
Test.stopTest();
system.assertEquals(null, unexpectedException, 'The operation should succeed');
// optionally run a query and assert on those results as well
No, your coverage is not adequate, even if you hit every line. You should look up and read about Cyclomatic Complexity, and aim to cover every major branch. Specifically, you do not have a test method which verifies a System Administrator is exempted from the rule. Similarly, you should verify that all users are still able to delete records where Receivable__c == false.
In every unit test, you should have unconditional assertions which verify the behavior you expect. Typically to verify that a validation is thrown, mine looks like:
DmlException expectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
expectedException = dmx;
Test.stopTest();
system.assertNotEquals(null, expectedException, 'The operation should fail');
// optionally run a query and assert on those results as well
The converse:
DmlException unexpectedException;
Test.startTest();
try
// perform DML which should fail
catch (DmlException dmx)
unexpectedException = dmx;
Test.stopTest();
system.assertEquals(null, unexpectedException, 'The operation should succeed');
// optionally run a query and assert on those results as well
edited 2 hours ago
answered 2 hours ago
Adrian Larson♦Adrian Larson
112k19123263
112k19123263
1
Point taken that I need to test for a sysadmin being exempted. But it's not possible to prevent a delete with a validation rule, that's why I have to write a trigger.
– Michael Kolodner
2 hours ago
Ah good point, I did not look at the trigger event.
– Adrian Larson♦
2 hours ago
add a comment |
1
Point taken that I need to test for a sysadmin being exempted. But it's not possible to prevent a delete with a validation rule, that's why I have to write a trigger.
– Michael Kolodner
2 hours ago
Ah good point, I did not look at the trigger event.
– Adrian Larson♦
2 hours ago
1
1
Point taken that I need to test for a sysadmin being exempted. But it's not possible to prevent a delete with a validation rule, that's why I have to write a trigger.
– Michael Kolodner
2 hours ago
Point taken that I need to test for a sysadmin being exempted. But it's not possible to prevent a delete with a validation rule, that's why I have to write a trigger.
– Michael Kolodner
2 hours ago
Ah good point, I did not look at the trigger event.
– Adrian Larson♦
2 hours ago
Ah good point, I did not look at the trigger event.
– Adrian Larson♦
2 hours ago
add a comment |
Another perspective on testing.
IMHO tests should confirm the planned behavior of the software: i.e. confirming customer visible/required behavior is priority #1. That is what your customer is paying for and wants to work. Start from those requirements when you write your tests, not from the code you have written to implement those requirements.
Sometimes you might write some tests that cover the building blocks that help you deliver that required behavior but that is essentially arbitrary implementation detail so is much less important.
Focussing on code coverage often leads people in a bad direction, where they have great code coverage but no assurance that the requirements are being met.
add a comment |
Another perspective on testing.
IMHO tests should confirm the planned behavior of the software: i.e. confirming customer visible/required behavior is priority #1. That is what your customer is paying for and wants to work. Start from those requirements when you write your tests, not from the code you have written to implement those requirements.
Sometimes you might write some tests that cover the building blocks that help you deliver that required behavior but that is essentially arbitrary implementation detail so is much less important.
Focussing on code coverage often leads people in a bad direction, where they have great code coverage but no assurance that the requirements are being met.
add a comment |
Another perspective on testing.
IMHO tests should confirm the planned behavior of the software: i.e. confirming customer visible/required behavior is priority #1. That is what your customer is paying for and wants to work. Start from those requirements when you write your tests, not from the code you have written to implement those requirements.
Sometimes you might write some tests that cover the building blocks that help you deliver that required behavior but that is essentially arbitrary implementation detail so is much less important.
Focussing on code coverage often leads people in a bad direction, where they have great code coverage but no assurance that the requirements are being met.
Another perspective on testing.
IMHO tests should confirm the planned behavior of the software: i.e. confirming customer visible/required behavior is priority #1. That is what your customer is paying for and wants to work. Start from those requirements when you write your tests, not from the code you have written to implement those requirements.
Sometimes you might write some tests that cover the building blocks that help you deliver that required behavior but that is essentially arbitrary implementation detail so is much less important.
Focussing on code coverage often leads people in a bad direction, where they have great code coverage but no assurance that the requirements are being met.
answered 1 hour ago
Keith CKeith C
98.3k1197226
98.3k1197226
add a comment |
add a comment |
Thanks for contributing an answer to Salesforce Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f262404%2fis-my-test-coverage-up-to-snuff%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Per this meta post, we would advise you to ask your question on CRSE for a more in-depth code review. Do, however, feel free to post in our Salesforce Meta so that we can be made aware of it. Thanks!
– sfdcfox
2 hours ago