You need to sign in to do that
Don't have an account?
Kamil Mieczakowski
Writing a test class for a for loop based method
Hi Guys, I wrote the below code and test method for it, but for some reason my test method is not providing sufficient coverage for deployment. I run out of ideas on how to increase the coverage of this test method. Any advice on how to do it?
Actual code:
Actual code:
public class standardiseWebsites { public static void standardiseWebsites(){ //extracting the host from the address for websites that have web-protocol (http:// and https://) list<Account> accts = [SELECT Website FROM Account WHERE Website LIKE 'http://%' OR Website LIKE 'https://%']; for (Account acct : accts){ string website = acct.Website; Url u = new Url(acct.Website); acct.Website = u.getHost(); update acct; } //removing first 4 digits of the address if it starts with 'www.' (non-web-protocol values) list<Account> accts2 = [SELECT Website FROM Account WHERE Website LIKE 'www.%']; for (Account acct2 : accts2){ string website = acct2.website; website = website.substring(4); acct2.website = website; update acct2; } } }Test:
@isTest public class standardiseWebsitesTest { static void standardiseWebsitesTest() { standardiseWebsites.standardiseWebsites(); } }
Something like this below.
@isTest
public class standardiseWebsitesTest {
@testSetup
public static void setupData()
{
Account acct = new Account();
acct.Name='Test Account';
acct.Website='http://www.google.com';
insert acct;
}
static testMethod void standardiseWebsitesTest() {
standardiseWebsites.standardiseWebsites();
}
}
All Answers
You have to use the below code to run the Test Class successfully and to have coverage on the Apex Code.
static testMethod void standardiseWebsitesTest() {
standardiseWebsites.standardiseWebsites();
}
Salesforce will not recognize the method as test method; unless you mention "testMethod" in the Test Class method.
You are missing generating test data.
Here is code which will help you to move forward: The code which I provide above will resolve your code coverage issue.
Moreove, I urge you to please refer following documents to learn more about test classes and get started:
1)Trailhead: https://trailhead.salesforce.com/en/modules/apex_testing/units/apex_testing_intro
2) Best Practices: https://s3.amazonaws.com/dfc-wiki/en/images/4/41/Apex_code_testing_webinar.pdf
By the way I also explained about you "void" method issue in your differnt thread. Please read that as well.
Thanks
Gulshan Raj
Something like this below.
@isTest
public class standardiseWebsitesTest {
@testSetup
public static void setupData()
{
Account acct = new Account();
acct.Name='Test Account';
acct.Website='http://www.google.com';
insert acct;
}
static testMethod void standardiseWebsitesTest() {
standardiseWebsites.standardiseWebsites();
}
}