143 votes
Accepted

Unit testing code which has logic around the CreatedDate

Spring '16 Release Notes document a new system method supporting this: Test.setCreatedDate(recordId, createdDatetime) Sets CreatedDate for a test-context sObject. This will definitely ...
user avatar
41 votes

How can Email Template be created in unit tests?

I assure you that it IS possible to create an EmailTemplate via Apex for unit testing. EmailTemplate validEmailTemplate = new EmailTemplate(); validEmailTemplate.isActive = true; validEmailTemplate....
user avatar
  • 2,101
41 votes
Accepted

Test.loadData() - undocumented (but useful) behavior loading relationships

Moving question into answer And the answer appears to be yes (a tip to a colleague of mine who discovered this) and it works for master-detail relationships too The Proof Account Contact with ...
user avatar
  • 63k
39 votes
Accepted

When to use Test.startTest?

Test.startTest() and Test.stopTest() exist primarily to allow you to reset the governor limits within the context of your test execution and to be able to test asynchronous methods. These two ...
user avatar
  • 22.4k
38 votes
Accepted

Insert Custom Metadata for Unit Test

At time of writing, it is not possible to insert test custom metadata, unless you use the Metadata API which would also present a challenge in a test scenario. That said, you should not need to. ...
user avatar
37 votes
Accepted

APEX test user creation

Taken from the documentation: Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user are not taken into account. The system method runAs enables ...
user avatar
  • 13.3k
37 votes
Accepted

How to create Hierarchy custom settings in Apex

You can use either of the two following constructs: insert new custSettings__c(SetupOwnerId=UserInfo.getOrganizationId(), SomeField__c='Some Value'); Or: custSettings__c settings = custSettings__c....
user avatar
  • 438k
37 votes
Accepted

Why Are Data Silos Important in Unit Tests?

I think the answer is quite simply one of consistency. It's also one of minimizing variations between environments we test in. This makes our test more consistent and repeatable. These are all things ...
user avatar
  • 40.5k
36 votes
Accepted

Compile Error: Method does not exist or incorrect signature: Test.startTest()

There is a good chance you actually created a class somewhere called Test. Find it and delete it.
user avatar
  • 6,059
34 votes
Accepted

How can I assign a permission set to a user in a test context?

This question is marked as unanswered, despite it was answered in the comments. Let's revise the answer here: PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = '<required permission ...
user avatar
  • 13.4k
30 votes

Why Are Data Silos Important in Unit Tests?

In two words: "bitter experience" I will admit that if you don't have any asserts in your code (another topic) you run a lesser risk but, the reasons all have to do with repeatability/predictability ...
user avatar
  • 63k
30 votes
Accepted

How to set a Date in apex test class?

You can do this using Apex' Date class: acc.effectiveDate__c = Date.newInstance(2016, 12, 9); For more information check out the documentation: Apex Developer Guide - Date Class
user avatar
30 votes
Accepted

How do I increase my code coverage, or why can't I cover these lines?

Code coverage is a measurement of how many unique lines of your code are executed while the automated tests are running. Code coverage percentage is the number of covered lines divided by the sum of ...
29 votes
Accepted

How to delete a Test Class WITHOUT using eclipse

You can do this with only the software that comes installed with Windows/Linux/Mac. These instructions will be for Windows. Create a Folder Make a folder on your desktop. You'll want this so you can ...
user avatar
  • 438k
28 votes

How to Test Messaging.sendEmail

You can use the Limits.getEmailInvocations method . Test.startTest(); methodThatSendsEmail(); Integer invocations = Limits.getEmailInvocations(); Test.stopTest(); system.assertEquals(1, ...
user avatar
  • 144k
27 votes

How to create mock class for multiple Callouts in single class

This need is covered in Testing Apex Callouts using HttpCalloutMock. Specifically, see the Testing multiple HTTP callouts section. Here's the example they use: public class MultiRequestMock ...
user avatar
  • 144k
26 votes

Is there any way of confirming that an @future method has been called/queued in a test class?

Yes! I love this question, as it's one of my pet peeves. People don't test @future calling methods because they don't know it's possible. Enter the magic of two key methods: Test.StartTest(); Test....
user avatar
  • 6,998
26 votes

Test a catch block for callout exception

There is exactly one way to do this. Scaffold a System.CalloutException in your mock: @TestVisible class UnauthorizedEndpointResponse implements HttpCalloutMock { public HttpResponse respond(...
user avatar
25 votes
Accepted

How to create mock class for multiple Callouts in single class

Here is perhaps the simplest form of a mock that deals with multiple requests. It is declared as an inner class of the test class so the idea is that it handles all the cases that the outer test ...
user avatar
  • 130k
24 votes

Test Class Apex Page Parameters

I realize this is a pretty old question. But in order for your parameter to work correctly, you have to instantiate the controller AFTER you set your page parameters. PageReference myVfPage = Page....
user avatar
  • 1,503
24 votes
Accepted

How Many Starttest() and StopTest() can I have in One Test Class?

You can have one StartTest / StopTest per test method. Each test method is executed independently. They may be on the same class but they share nothing and do not see side effects from each other. ...
user avatar
24 votes
Accepted

How to test a scheduler which runs a batch?

I had a similar problem before which I solved by explicitly calling the execute method of my Schedulable class. Try something like this: Test.startTest(); AccountBatchScheduler abs= new ...
user avatar
  • 5,258
23 votes

Apex Code Coverage: Test classes are included with 0% in overall code coverage calculation

It sounds like you may have a specific problem related to mocking; however, for those experiencing the general problem stated in the question title, "Test classes are included with 0% in overall code ...
user avatar
  • 11.1k
22 votes

Insert Custom Metadata for Unit Test

New in Winter 19! Instantiate Custom Metadata Types in Apex Example from the release notes... How: In this example, the first method is instantiating a custom metadata record, but no records are ...
user avatar
  • 5,185
22 votes
Accepted

How to mock a Database.saveresult?

You can create "fake" system objects, but, of course, be wary of doing so in a way that will break their internal implementation. Here's an example of a successful save: Database.SaveResult sr = (...
user avatar
  • 438k
22 votes
Accepted

How do I write an Apex unit test?

This answer is not intended to teach you everything about writing unit tests, nor to specifically answer every question, but to provide a quick summary and links to the resources that will help you ...
21 votes

1.how to stop run all tests? 2.validation running for about 6 hours in production. how to stop it?

Setup->Develop->Apex Test Execution->Select all or Required test classes->Click on "Abort" button.
user avatar
21 votes

Unit Test: You have uncommitted work pending. Please commit or rollback before calling out

You can't do a web service callout after a DML operation in the same transaction. try this code:- @isTest static void sometimes_salesforces_sucks() { My_Object__c foo = new My_Object__c(Name='...
user avatar
  • 2,227
21 votes

Invalid Cross Reference Key : Record Type ID value isn't valid for User: 012v00000008f4nuBB

Profiles have record type settings. This error means that the user has a profile for which that record type is not enabled. You need to make sure the profile you're using has access to the desired ...
user avatar
  • 438k
21 votes
Accepted

How to Create Opportunity Line Items in Test Classes

When working with Opportunity Line Items in Test Classes, you need to first make sure you have a pricebook, then you need to create a product, then you need to create a pricebook entry and then you ...
user avatar

Only top scored, non community-wiki answers of a minimum length are eligible