120

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 complement the loadData() and deserialize() techniques. Account account = new Account(Name = 'Test'); insert account; Datetime yesterday = Datetime.now().addDays(-1);...


74

You can create sObjects in memory with arbitrary CreatedDate values by using JSON.deserialize. This doesn't enforce the normal read-only field attributes that prevent you from setting a createdDate value. However you can't commit arbitrary CreatedDate values to the database (or else it would be a serious security issue). An example of doing so : String ...


57

It isn't available now, but I'm reviewing the Winter 13 release notes and came across a new feature that sounds like it might work. I'm assuming this is what Rich alluded to in his comment above. The new feature is called Loading Test Data from Static Resources. You'd load test data like so: List<sObject> ls = Test.loadData(Account.sObjectType, '...


48

You can resolve this in your test class by using System.runAs. System.runAs ( new User(Id = UserInfo.getUserId()) ) { ...your setup-object DML... } If you need to do this in a non test scenario @future, Batch Apex, apex:actionFunction or something as simple as user button flow, it can be used to separate the transactions. The Salesforce documentation ...


42

The following code will test that you are correctly saving the account record in the constructor (which is all your extension does so far): public static testMethod void testmyExtension() { Account a = new Account(name='Tester'); insert a; ApexPages.StandardController sc = new ApexPages.standardController(a); myExtension e = new myExtension(...


39

Here's the fake ID test utility method as used in my DF13 "Tests and Testability" session: public class TestUtility { static Integer s_num = 1; public static String getFakeId(Schema.SObjectType sot) { String result = String.valueOf(s_num++); return sot.getDescribe().getKeyPrefix() + '0'.repeat(12-result.length()) + result; ...


37

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 lookup relationship AccountId and custom lookup Alternate_Account__c Here's the CSV file for the Account - note the values of 0 and 1 for the test Account.ID rows: ...


37

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 that are helpful should we need to diagnose or troubleshoot a problem during deployment. When we generate our own data, that eliminates a variable between ...


35

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 statements cannot be called more than once within a testMethod. They are not required to be used but in some situations may be critical. Asynchronous (@future) calls ...


34

Setting up the RestContext manually in this case is a bit like Test.setCurrentPage if your Apex Controller code looks for the current page for what it needs. And so in this case it helps emulate what your service is expecting at runtime. In the case of designing Rest services, they receive parameters via a number of inputs. A key one is the URI (as parts ...


32

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.getOrgDefaults(); settings.SomeField__c = 'Some Value'; upsert settings custSettings__c.Id; Either way, basically you need to make sure SetupOwnerId is set to ...


31

There's a few ways to do this. My personal preference is to generate a different Blob for the body of the page depending on whether my code is running in the test context: So if I have a reference to the page in variable pr: Blob content; if (Test.IsRunningTest()) { content=Blob.valueOf('UNIT.TEST'); } else { content=pr....


31

I assure you that it IS possible to create an EmailTemplate via Apex for unit testing. EmailTemplate validEmailTemplate = new EmailTemplate(); validEmailTemplate.isActive = true; validEmailTemplate.Name = 'name'; validEmailTemplate.DeveloperName = 'unique_name_addSomethingSpecialHere'; validEmailTemplate.TemplateType = 'text'; validEmailTemplate.FolderId = ...


31

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 you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. The runAs method doesn’t ...


30

I had a suspicion (remember reading somewhere) that Field History Tracking cannot be tested in a Unit Test Class. A bit of Developer Board surfing threw up this post which confirmed that since none of the data is actually committed during a Unit Test, its not possible to Unit Test Field History Tracking. http://boards.developerforce.com/t5/Visualforce-...


30

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 and the advantages therein. Every deployment of the same test class should run the same environment every time. Today, tomorrow, and 5 years from now. Here ...


29

From http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_test.htm?SearchType=Stem This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage to creating a separate class for testing as opposed to adding test methods to an existing class is that classes defined with isTest don't ...


28

Apex Trigger Code Testing Writing test code to invoke Apex Trigger logic is a requirement, even if you have other tests that cover other aspects of the code called from it, such as utility or library methods in other Apex classes. As such you must have at least one Apex test perform the require DML operations on the object to invoke the trigger logic, no ...


28

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 keep your files in order. Create package.xml Open Notepad (Start > Accessories > Notepad). Copy the following text into the text editor: <?xml version="1....


28

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. Custom Metadata is Metadata and as such is not affected by the SeeAllData annotation. See this article dedicated to testing custom metadata.


25

There are a couple of decent Dreamforce presentations here: Team Development: Possible, Probable, and Painless and Continuous Integration in the Cloud. We ran into some issues with this in practice and there was no way to get true automation (i.e., set it and forget it). We were also setting it up with Selenium. Here were the issues that I remember. ...


25

Salesforce passes in the HTTPRequest made by the logic your testing into the mock implementation to help with this type of requirement. So in the HttpCalloutMock.respond method implementation. You can call req.getBody() and condition the response based on that, here is an example... @IsTest private with sharing class MultiHttpMockTest { public class ...


25

The doInvoke method on the mock interface passes in the stub and request parameters. You can use these to condition to dispatch the mock logic to various other mock implementations, while only registering a single mock implementation. Test.setMock(WebServiceMock.class, new MockDispatcher()); public class MockDispatcher implements WebServiceMock { ...


24

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.StopTest(); When you utilize these methods -- and you should! they do a couple of key things for you. they reset your governor limits so you can test if your ...


23

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 coverage calculation", there is another cause for this issue. As @Bujji stated in his answer, it does occur (as of Spring 15) that changing a class from a non-...


23

There is a good chance you actually created a class somewhere called Test. Find it and delete it.


23

There is exactly one way to do this. Scaffold a System.CalloutException in your mock: @TestVisible class UnauthorizedEndpointResponse implements HttpCalloutMock { public HttpResponse respond(HttpRequest request) { CalloutException e = (CalloutException)CalloutException.class.newInstance(); e.setMessage('Unauthorized endpoint, please ...


23

You can use the Limits.getEmailInvocations method . Test.startTest(); methodThatSendsEmail(); Integer invocations = Limits.getEmailInvocations(); Test.stopTest(); system.assertEquals(1, invocations, 'An email should be sent'); What to do about NO_MASS_MAIL_PERMISSION? You can use the Messaging.sendEmail method with the optional allOrNone ...


22

Starting summer 14, you can now use Test.getStandardPricebookId() to get the Id of the current Pricebook. This works in Test classes only. Here is a sample on how this works in practice @isTest public class PriceBookTest { // Utility method that can be called by Apex tests to create price book entries. static testmethod void addPricebookEntries() { ...


21

Have you checked the "Access to Send Email" option under Administration Setup - Email Administration - Deliverability? It's new feature in Spring 13.


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