19

As I have just rewritten our internal unit test design patterns I've tested this quiet thoroughly and believe I have a proper grasp on how @testSetup currently handles governing limits within the test class In short, any DML statement within the context of @testSetup will not count against your overall test class limits but SOQL statements will. For ...


18

You can use following: Test.setCreatedDate(recordId, createdDatetime); Sets CreatedDate for a test-context sObject. Datetime testingday = Datetime.now().addDays(-3); Test.setCreatedDate(MyCustomObject__c.Id, testingday);


16

A major reason to use @TestSetup is the situation where you have many tests that require the same baseline of data. The @TestSetup method runs once and all its data is available to all the test methods in the class. Any changes made by a test method are rolled back but the @TestSetup data isn't. The benefit is faster test running because the baseline data ...


11

The product manager (I think) at the time this feature was introduced explains it like this: If you want information that is common to all tests, it can be inserted in the test setup method and queried in each test method. The idea here is not to reduce the number of SOQL queries, it is to reduce the amount of data being inserted into the system. ...


11

I use both. Why would you have to choose one over the other? @testSetup is a way to reduce test execution time by reusing the data created once in all the test methods of a test class. TestFactory is to reuse same data in multiple test classes. Ex: @isTest private class AvinashTest { @testSetup static void testSetup() { Test.startTest(); ...


10

The compilation problem is that the definition of u is local to one method and you are trying to reference it in a another method. You can get a local reference to that user to avoid the compilation error like this: static testMethod void testOppsPt1(){ User u = [select Id from User where Username = 'astest@wexeurope.com']; List<Opportunity> ...


9

User u = new User(); //put the user details you want for this user. insert u; System.runAs(u) { /* your record insert here */ insert Account; } The account will have the createdById set as the User u;


9

This has nothing to with @testSetup. My answer from a similar question which is valid for this one also: What could have happened is, test class was created without @isTest annotation (at this point the class has been added to the code coverage table) and @isTest was added later (but this doesn't remove the class from the table). This usually happens if ...


8

To be honest, the increase in speed is about the only tangible benefit to us (as developers). Salesforce themselves arguably sees more benefit from people using this annotation than we developers (directly) do. If it's faster for us, that means that it also places less load on Salesforce's pods. As others (including yourself) have noted, it doesn't save ...


7

Set up your test data in @testSetup. To avoid using your test governor limits, start with Test.startTest(): @isTest class MyUnitTestClass { @testSetup static void testSetup() { Test.startTest(); // Do your DML operations here Test.stopTest(); } @isTest static void test() { // You have to re-query your records // Account a = [SELECT ...


7

Your @testSetup method is run once, before any of your tests are run, and any changes made to those records are rolled back between tests. From the documentation: By setting up records once for the class, you don’t need to re-create records for each test method. Also, because the rollback of records that are created during test setup happens at the end ...


7

ApexMocks uses the Stub API. The pro of ApexMocks is that you get a ready-to-use Stub API framework for your own tests, while the con would be that it may have a lot of features you don't need (code bloat). If you want, you can take just the parts you need and trim it down, use it as an example for your own in-house framework, or do something else entirely. ...


6

My hunch is that when you enable Independent Auto-Number Sequence Test Option, the auto number sequence gets reset for every transaction. Since @testSetup runs in a different context, it should be a separate transaction from the unit test. Hence, the unit test itself gets a fresh sequence.


6

You can't set the accountId of Quote directly. It will be set by Salesforce with the accountId of the Opportunity related to this Quote. Ran this code and print the quote variable and it have the accountId assigned. Account acc = new Account(name='Test Acc'); insert acc; Opportunity o = new Opportunity(AccountId = acc.Id,name = acc.name,closedate = system....


6

That's not how unit tests work. The lines tested in each test will be cumulatively covered. You can view the results for an individual test (assuming you turn off "Store Only Aggregate Test Data"), but the coverage will still be correct. I wrote a mock up in my developer org that proves it works correctly. However, if you're having problems, I recommend ...


6

You can use the new compileAndTest task to run tests without a package.xml. Your build.xml can look like this: <project name="salesforce" xmlns:sf="antlib:com.salesforce"> <property environment="env" /> <property file="build.properties" /> <target name="compileAndTest"> <sf:compileAndTest username="${username}" ...


6

From my humble point of view, the biggest advantage is to not have to duplicate code and have a consistent set of data that you can use for all the tests in a given class (or classes). However, there are a couple of other good use-cases. Your code is a lot easier to read, having one place where all the data is created If you have other test classes that ...


6

It is a correct way. I would, however, like to identify few benefits of @testSetup below Use this annotation if you want to create test data once and use it in all test methods of your class. Therefore, you don't need to recreate the data again. Records created in a test setup method are rolled back at the end of test class execution. @testSetup methods ...


6

Yes, you must re-query the data. Sometimes you might use constant strings to pull in, for instance a custom setting: static final String SETTING_NAME = 'foo'; @TestSetup static void setup() { insert new MySetting__c(Name=SETTING_NAME); } static testMethod void testBar() { MySetting__c relevantSetting = MySetting__c.getInstance('foo'); } Often, ...


6

@TestSetup is only applicable in the same test class. You should take this approach to make your TestDataFactory class reusable and that setup() method can be accessed from @TestSetup method of calling class. public class FunctionalClass { //logic that needs to be tested } @IsTest public class TestFunctionalClass { @TestSetup static void ...


6

This is a method you would have known about if you'd seen my previous answer on the subject. We use this internally because without using this technique, we continually run into governor limits on some of our larger tests. Several developers, including myself, have independently found this feature, and it's allowed us to continue building our internal ...


6

You can't set up an OrgWideEmailAddress. Attempting to do so gives this error: DML operation Insert not allowed on OrgWideEmailAddress Fortunately, you can see them perfectly fine without SeeAllData=true. I even took the time to verify it with a simple unit test: // This class is in version 43.0, SeeAllData=false by default @isTest class q224877 { @...


5

The bottom line is that you can't. As explained in the product management comment to this Remember static variables set during testSetup annotated methods idea: We intentionally clear out static variables between each test method. If we did not, each test would cease to be an independent trial. You could modify the static in one test method, which ...


5

I've heard many people asking similar questions with the same issue. This is a bug with the displayed code coverage but will not be factored into minimum coverage deployment calculations. This is most likely caused by initially creating/saving your test factory class without the @isTest prefix. If you follow these instructions you can remove the incorrect ...


5

You can take help from testmethod. Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in any test method in the test class. Test setup methods are useful and can be time-saving when you need to create a common set of records that all test methods operate on or prerequisite data. Reference:


5

The Apex Developer Guide does indicate speed is the primary motivation, especially in the face of data-volume: Using Test Setup Methods Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in every test method in the test class. Test setup methods can be time-saving when you need to ...


5

Your setup definitely can run future methods, so they are not ignored entirely. This test passes for me on cs14 using any API Version between 35 and 40: @IsTest public class DemoFuture { @TestSetup static void setupData() { createSomeData(); } @future public static void createSomeData() { SObjectFactory.create(...


5

Your trigger l ine: ServiceCredentials__c cred = ServiceCredentials__c.getValues('BillingServiceCredential'); is fetching a Custom Setting. You need to mock values of this custom setting in your testmethod. You should not rely on org data (seeAllData=true) except in the most unusual of circumstances. You can mock custom settings like any other SObject by ...


5

I would say no. This sounds like an attempt at "clever" programming (which I'll get back to). If you're using an @future method (or any async method) to do test setup, you'd need to wrap the call to your setup inside Test.startTest() and Test.stopTest() to ensure that the async method actually executes before your test ends (in effect, making it a ...


5

As you haven't supplied any code this is only a guess based on a typical problem... When something happens in the database changed field values (with the exception of object Id fields when records are created) are not automatically brought back into the Apex code. So you have to requery the data to see the new values.


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