You are on page 1of 23

What to Test In Apex?

Salesforce.com recommends the following components need to test.

1. Single Records:
This includes testing to verify that a single record produces the correct,
expected result
2. Bulk Records:
Any apex code, whether a triggers, a class or on extension may be used
for 1to 200 records we must test not only the single record case, but the bulk
cases as well.
3. Positive scenarios:
This type of component testing expect a system to save a record without error.
4. Negative scenarios:
This type of component testing expect a system to give error.
5. Restricted User:
Test whether a user with restricted access to the objects used in code sees
the expected behavior, i.e whether they can run the code or receive error
messages.
How is a test method defined?
A test method is defined as mentioned below:-
Syntax:

1 static testMethod void testMethodName(){….. Code here ……..}

How is code coverage calculated?


 
Code coverage percentage is a calculation of the number of covered lines divided
by the sum of the number of covered lines and uncovered lines.
 
Note: Comments blank lines,System.debug() statements and curly brackets are
excluded
 
Multiple statements on one line are counted as one line for the purpose of code
coverage.
 
Which classes are excluded from code coverage calculation?
Test classes (classes that are annotated with @isTest) are excluded from the code
coverage calculation.
Where the code coverage is stored?
Code coverage is stored in two Lightning Platform Tooling API objects:
ApexCodeCoverageAggregate:
It stores the sum of covered lines for a class after checking all test methods that
test it
ApexCodeCoverage:
Stores the lines that are covered and uncovered by each individual test method.
How to retrieve code coverage information?
We can query these objects by using SOQL and the Tooling API to retrieve
coverage information. Using SOQL queries with Tooling API is an alternative way
of checking code coverage and a quick way to get more detail.
Code coverage best practice?
Some of the best practices are:
Code coverage should not depend on the existing data in the org, i.e. sellAllData
should not be true
For testing trigger and batch class we should do bulk testing with at least 200
records.
Testing should be done for the entire scenario not only for the code coverage
Why code coverage differs between sandbox and production?
Sandbox and production environments often don’t contain the same data and
metadata, so the code coverage results don’t always match.
@isTest annotation ?
Use the @isTest annotation to define classes and methods that only contain code
used for testing our application.
SeeAllData=true annotation ?
Use the @isTest(SeeAllData=true) annotation to grant test classes and individual
test methods access to all data in the organization.
Considerations for the @IsTest(SeeAllData=true) Annotation?
If a test class is defined with the isTest(SeeAllData=true) annotation, this
annotation applies to all its test methods whether the test methods are defined
with the @isTest annotation or the test method keyword.
The isTest(SeeAllData=true) annotation is used to open up data access when
applied at the class or method level. However, using isTest(SeeAllData=false) on
a method doesn’t restrict organization data access for that method if the
containing class has already been defined with the isTest(SeeAllData=true)
annotation. In this case, the method will still have access to all the data in the
organization.
OnInstall = true notation?
Use the @IsTest(OnInstall=true) annotation to specify which Apex tests are
executed during package installation. This annotation is used for tests in
managed or unmanaged packages.
(isParallel=true)?
Use the @isTest(isParallel=true) annotation to indicate test classes that can run
in parallel. Default limits on the number of concurrent tests do not apply to these
test classes.
Can we use (SeeAllData=true) and (isParallel=true) in same apex test
method?
@isTest(SeeAllData=true) and @isTest(isParallel=true) annotations cannot be
used together on the same Apex test method.
Which Objects can we access without using seeAllData=true?
We use seeAllData = true to get real-time data in test class, but without using
this also we can get the data from following objects.
User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass,
ApexComponent , ApexPage and custom metadata types.
Why it is recommended to avoid using seeAllData=true?
Enabling this seeAllData = true exposes the data from the database to the test
class. It is recommended not to use as the code coverage of we apex class or
trigger will now be dependent on the data which is present in org and depending
upon that the code coverage may change
Does Salesforce count calls to system.debug() against the code coverage?
No, Salesforce does not count it against the code coverage.
Why to create separate class for testing purpose?
Advantage of creating a separate class for testing as opposed to adding test
methods to an existing class is that classes defined with isTest don’t count against
our organization limit of 6 MB for all Apex code.
What are the considerations of using isTest annotation?

 Classes and methods defined as isTest can be either private or public.

 Classes defined as isTest must be top-level classes.

 One advantage to creating a separate class for testing is that classes defined

with isTest don’t count against our organization limit of 6 MB for all Apex

code.

 We can also add the @isTest annotation to individual methods

 Classes defined as isTest can’t be interfaces or enums

 Methods of a test class can only be called from a running test, that is, a test

method or code invoked by a test method, and can’t be called by a non-test

request.

 Test methods can’t be used to test Web service callouts. Instead, use mock

callouts

 We can’t send email messages from a test method


 Methods of a public test class can only be called from a running test, that is,

a test method or code invoked by a test method, and can’t be called by a

non-test request.

@testSetup annotation?
 
Methods that are annotated with @testSetup are used to create test records once
and then access them in every test method in the test class.  
Test setup methods enable us to create common test data easily and efficiently.
By setting up records once for the class, we don’t need to re-create records for each
test method.
Example: For example, we have a test class, It has two test methods and each
test method required 5 account records.So without creating 5 records for each
test method, we will create a new method with annotation @testSetup then
create only 5 account records. These records can access all test methods using
SOQL query in that test class.  
 
What are the things to remember when we use @testSetup method?
All database changes are rolled back at the end of a test. We can’t use this method
on records that existed before the test executed. We also can’t use setCreatedDate
in methods annotated with @isTest(SeeAllData=true), because those methods have
access to all data in the org. The both parameters (Id recordId, Datetime
createdDatetime) of this method are mandatory.
What is the difference between testMethod and @isTest?
@isTest annotation is used to define the test classes which contains code to test
our application and these classes does not count against our overall code
coverage.
testmethod keyword is used to define apex test methods. Also test methods can
be defined in any apex class.
 
@testVisible annotation?
 
Some methods are declared as private so we won’t be able to call them outside
the class. However, sometimes we really want to be able to invoke it from a unit
test method.
To resolve this, we can mark the method with a @TestVisible annotation. Then
although it is still private, it is invokable from our unit test methods.
How is a class defined as a test class ?
Use @isTest annotation to define a test class.
What is the use of System.runAs() method?
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
us 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
enforce user permissions or field-level permissions, only record sharing.
The following items use the permissions granted by the user specified with runAs
running as a specific user:
 
Dynamic Apex Methods using with sharing or without sharing

Shared records
The original permissions are reset after runAs completes.The runAs method
ignores user license limits.
Can we use system.run as in all the methods?
System.runAs() must be used only in a test method
Can runAs help in solving mixed DML error?
We can also use the runAs method to perform mixed DML operations in our test
by enclosing the DML operations within the runAs block. In this way, we bypass
the mixed DML error that is otherwise returned when inserting or updating setup
objects together with other sObjects. The moment we do System.Runas(User u),
all the permissions of the user u are re-read form the database and re-applied to
the running context
What is Test.isRunningTest()  method?
The Test.isRunningTest()  method is used to identify, if the piece of code being
executed is invoked from a Test class execution or from other artefacts such as a
Trigger, Batch Job etc. Returns true if the code being executed is invoked from a
test class otherwise returns a false.
Example:
Performing web service callouts in Apex are not supported within Test
Code. Hence we could use the Test.isRunningTest() to conditionally identify and
route the execution of a code block that calls the Test Mock framework to simulate
a mock, callout response.
Use Case of Test.isRunningTest() method
When we are setting up test data from Apex test method, we need a way to
disable the triggers that will fire. It might cause “LimitException: “Too many
SOQL
queries: 101″. In this case, the triggers are not the target of the test case, hence
this scenario will cause the test method to fail. It is not necessary to disable the
trigger for every test case, instead we can use isRunningTest().
Setup up the trigger by leveraging isRunningTest(). isRunningTest() – Returns true
if the currently executing code was called by code contained in a test method,
false otherwise. Use this method if we need to run different code depending on
whether it was being called from a test
Other Usage scenarios
1. To ensure the trigger doesn’t execute the batch if Test.IsRunningTest() is true,
and then test the batch class with it’s own test method.

2. Testing callouts – in our callout code we check to see if we‘re executing within a
unit test context by checking Test.isRunningTest() and instead of getting your
callout response from an HttpResponse.send() request, you return a pre-built test
string instead.
 
What is the use of System.Assert/System.AssertEquals Methods?
These methods are used to ensure that the Apex code executes and returns the
expected value.
System.Assert: It accepts two parameter: First one (mandatory) is the condition
test and the second one is used to display a message in case the condition fails.
Syntax: System.assert(var1 == var2,”msg”)
System.AssertEquals: It accepts three parameters; the first two (mandatory) are
the variables that will be tested for equality or inequality, and the third (optional)
one is used to display a message in case the condition fails.
Syntax: System.assertEquals(var1, var2,”msg”);
What is the use of Test.startTest/Test.stopTest method?
Test.startTest and Test.stopTest are used for asynchronous apex, like Batch Apex
and Future calls. Calling method(s) between Test.startTest and Test.stopTest
ensure that any asynchronous transactions finish executing before Test.stopTest()
exits.
 
startTest()
Marks the point in our test code when our test actually begins. Use this method
when we are testing governor limits.
Usage
We can also use this method with stopTest to ensure that all asynchronous calls
that come after the startTest method are run before doing any assertions or
testing. Each test method is allowed to call this method only once.
stopTest()
Marks the point in our test code when our test ends. Use this method in
conjunction with the startTest method.
Usage
Each test method is allowed to call this method only once. Any code that executes
after the stopTest method is assigned the original limits that were in effect before
startTest was called.
Example: if our class makes 98 SOQL queries before it calls startTest, and the
first significant statement after startTest is a DML statement, the program can
now make an additional 100 queries. Once stopTest is called, however, the
program goes back into the original context, and can only make 2 additional
SOQL queries before reaching the limit of 100
Why would a developer use Test.startTest() and Test.stopTest()?
1. To avoid Apex code coverage requirements for the code between these lines.
2. To start and stop anonymous block execution when executing anonymous Apex
code
3. To indicate test code so that it does not impact Apex line count governor limits
4. To create an additional set of governor limits during the execution of a single
test class
Test.setCreatedDate?
 
Set the Created date field value is used to test records in Salesforce test classes

using setCreatedDate(Id recordId, Datetime createdDatetime) method.


What are considerations while using
setCreatedDate?
 
All database changes are rolled back at the end of a test. We can’t use this
method on records that existed before the test executed.
We also can’t use setCreatedDate in methods annotated with
@isTest(SeeAllData=true), because those methods have access to all data in the
org. The both parameters (Id recordId, Datetime createdDatetime) of this method
are
mandatory.
How to test asynchronous callout?
 
Because Apex tests don’t support making callouts, we can simulate callout
requests and responses. When we are simulating a callout, the request doesn’t
get sent to the external service, and a mock response is used.
 
To simulate callouts in continuations, call these methods of the Test class:
Test.setContinuationResponse sets a mock response, and
Test.invokeContinuationMethod causes the callback method for the continuation
to be executed.
 
How to test a Web Service Callouts?
By default, test methods don’t support web service callouts, and tests that
perform web service callouts fail. To prevent tests from failing and to increase
code coverage, Apex provides the built-in WebServiceMockinterface and the
Test.setMock method.
 
When we create an Apex class from a WSDL, the methods in the auto-generated
class call WebServiceCallout.invoke, which performs the callout to the external
service. When testing these methods, we can instruct the Apex runtime to
generate a fake response whenever WebServiceCallout.invoke is called. To do so,
implement the WebServiceMock interface and specify a fake response for the
Apex
runtime to send
How many types of Assert Statements are there and what is their purpose?
Assert statements are used to compare expected value with the actual value.
There are three types of assert statements :
 
assertEquals(expVal, actVal); returns true if expVal Matches actVal.
assertNotEqual(expVal, actVal); returns true if expVal does not match actVal.
assertEquals(expVal > actVal); returns true if the condition is satisfied.
Can we populate history tables from unit testing?
We can’t populate the history tables from unit tests as this happens after a
transaction is committed to the database, which doesn’t happen in the test
context, rather the entire transaction is rolled back at the end of the test
How to test future method?
To test future methods make our call to any future method between
Test.startTest(); and Test.stopTest(); statements and the future method will
return when Test.stopTest(); is called.
What is a good practice of testing Batch class?
We should always test batch class with good amount of data
(minimum 200 records) in our test class.
Use Test.startTest() and Test.stopTest() to test batchable classes
When testing can i use existing data?
 

By design, test classes do not have access to our org’s data unless we explicitly set

SeeAllData=true

 We have no way of guaranteeing the data we retrieve will accurately run

 We have no way of guaranteeing the data we expect will exist through we

tests.

By setting up we own test data we :

 We remove problems with locks

 Know exactly what is present with regards to good and bad data
 Can help improve our testing by having proper edge cases tested

 Remove dependencies outside of our control

How to test class for batch apex making http apex callouts?
We should be able to do this using HttpCalloutMock and Test.startTest/stopTest.

What are the testing best practices?

1. Test class must start with @isTest annotation if class class version is more than
25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no
email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure
that every use case should covered including positive, negative,bulk and single
record .
Single Action -To verify that the the single record produces the correct an expected
result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200
records .
Positive behavior : Test every expected behavior occurs through every expected
permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .10.
Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access
specifier .
14. classes with @isTest annotation can’t be a interface or enum .
15. Test method code can’t be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test
classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out
mock .
19. You can’t  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType,
ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account>
accList=Test.loadData(Account,SobjectType,’ResourceName’).
23. Create TestFactory class with @isTest annotation to exclude from organization
code size limit .
24. @testSetup to create test records once in a method  and use in every test
method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com
IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500
or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not
taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the
process .

Interview Questions and Answers on


Test Classes
1. What is the purpose of writing the test class?

After developing an apex class or apex trigger we should write the unit tests and ensure that we are
able to execute at least 75% of the lines of code.
If you are moving the code from sandbox to sandbox regarding code coverage you won't face any
issue.
If you are moving the code from sandbox to production, you need to include all the test classes at the
time of deployment and salesforce will run all the test classes which you included for the deployment as
well as test classes which are already present in production, if the code coverage is less than
75% deployment will fail.

2. Is it possible to write test code inside of an apex class or apex


trigger?
we cannot write test code (test methods) inside of the apex trigger.
From API Version 28.0, we cannot write the test methods inside of an apex class which is not decorated
with @isTest.
We can write test methods only in a class which is decorated with @isTest.
Note: We have a governor limit for the overall Apex Code size of the organization which is of 3 MB. If we
decorate a class with @isTest annotation Apex Code Size governor limit will be bypassed.

3. Syntax of testMethod?
@isTest
private class MyTestClass {

static testMethod void myTest1() {


}

static testMethod void myTest2() {


}

Note: Test Class can be either public or private.

4. What is the purpose of seeAllData?


By default test class cannot recognize the existing data in the database.
if you mention @isTest(seeAllData = true) then test class can recognize the existing data in the
database.
See the below examples -
 From a List Custom Settings we cannot fetch the existing data without seeAllData = true in test
class.
 Suppose you have a custom object called 'CustomObject__c' and it contains many records, we
cannot fetch the existing data without seeAllData = true in test class.
Note: It is not recommended to use seeAllData = true for a test class. Based on the existing data in
database code coverage will impact.

5. What is the purpose of Test.startTest() and Test.stopTest()?


Test.startTest() and Test.stopTest() maintains fresh set of governor limits. Assume that you are
consuming 99 SOQL queries outside of Test.startTest() and Test.stopTest() then if you include any SOQL
inside of Test.startTest() and Test.stopTest() count will start from 1.
Per testMethod we can use Test.startTest() and Test.stopTest() only for one time.
To execute asynchronous methods synchronously we can call those methods from inside of
Test.startTest() and Test.stopTest().

6. What is the purpose of system.runAs()?


By default test class runs in System Mode. If you want to execute a piece of code in a certain user
context then we can use system.runAs(UserInstance). For more details refer 2nd question in
visualforce category.
To avoid MIXED-DML-OPERATION error we can include DML statements inside of system.runAs(), still
the error persists keep DML statements inside of Test.startTest() and Test.stopTest().

7. What are the assert statements?


What is the purpose?
To compare Actual value and Expected value we use assert statements.
Types of assert statements
1. system.assertEquals(val1,val2): If both val1 and val2 are same then test class run successfully
otherwise test class will fail.
2. system.assertNotEquals(val1,val2): If both val1 and val2 are not same then test class run
successfully otherwise test class will fail.
3. system.assertEquals(val1> val2): If the condition satisfied then test class run successfully
otherwise test class will fail.

8. What is the purpose of Test.isRunningTest()?


Sometimes we cannot satisfy certain if conditions for the apex classes, in those situations on those if
conditions we can add Test.isRunningTest separated with or condition. Example: if(condition ||
Test.isRunningTest())

9. What is the purpose of @TestVisible?


Sometimes in test classes we need to access a variable from Apex Class, if it is private we cannot access
for that we will replace private with public. for this reason we are compromising the security. To avoid this
before the private variables in apex class we can include @TestVisible so that even though variable is
private we can access from the test class.

10. What are the test class best approaches?


1. We should not depend on the existing data in the database. We should create the test data for all
the possible scenarios. Note: Profiles and recordTypes cannot be created programmatically, we can
query from the database. For the remaining objects including users we should create the test data.
2. While testing apex triggers and batch classes, we should do bulk testing at least with 200
records.
3. We should test for all the positive and negative scenarios.
Testing Apex
salesforce.com strongly recommends that you use a test-driven development process, that is, test
development that occurs at the same time as code development.

Why Test Apex?


* Testing is key to the success of your application, particularly if your application is to be deployed to
customers.
* If you validate that your application works as expected, that there are no unexpected behaviors, your
customers are going to trust you more.
* There are two ways of testing an application.
  1. One is through the Salesforce user interface, important, but merely testing through the user interface
will not catch all of the use cases for your application.
  2. The other way is to test for bulk functionality: up to 200 records can be passed through your code if
it's invoked using the Force.com Web services API or by a Visualforce standard set controller.
* You will have additional releases of it, where you change and extend functionality.
* If you have written comprehensive tests, you can ensure that a regression is not introduced with any
new functionality.

Before you can deploy your code or package it for the Force.com AppExchange, the following must be
true:
• 75% of your Apex code must be covered by unit tests, and all of those tests must complete
successfully.
Note the following:
- When deploying to a production organization, every unit test in your organization namespace is
executed.
- Calls to System.debug are not counted as part of Apex code coverage in unit tests.
- While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage
of code that is covered.
- Instead, you should make sure that every use case of your application is covered, including positive and
negative cases, as well as bulk and single record.
- This should lead to 75% or more of your code being covered by unit tests.
• Every trigger has some test coverage.
• All classes and triggers compile successfully.
Note:
Salesforce runs all tests in all organizations with Apex scripts to verify that no behavior has been altered
as a result of any service upgrades. 

What to Test in Apex


Salesforce.com recommends that you write tests for the following:
Single action
Test to verify that a single record produces the correct, expected result.
Bulk actions
Every Apex script, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You
must test not only the single record case, but the bulk cases as well.
Positive behavior
Test to verify that the expected behavior occurs through every expected permutation, that is, that the user
filled out everything correctly and did not go past the limits.
Negative behavior
There are likely limits to your applications, such as not being able to add a future date, not being able to
specify a negative amount, and so on.
You must test for the negative case and verify that the error messages are correctly produced as well
as for the positive, within the limits cases.
Restricted user
Test whether a user with restricted access to the sObjects used in your code sees the
expected behavior.
That is, whether they can run the code or receive error messages.

Interview Questions on Test Class


1) What is test class in  Salesforce? 

.When we are moving code from sandbox to production org we need to write a test class.

.Whatever code we have written we need to ensure that each and every condition is correct

and we can create a dummy data for it.

.The code must have 75% coverage to deploy it to production.

Points to remember.
1)Test class does not have access to organization data but if we write
@isTest(seeAllData=true),

then we can access data in the test class as well.

2)As every organization have code limit by writing @isTest above test class, the limit will
not be considered.

3)Every test class has a method declared with testmethod keyword and is static.

Syntax:

static testmethod void methodname()

2) What is test.starttest() and test.stoptest()? 


.Whatever test we are performing we write the test inside of Test.starttest() and
Test.stoptest.

.Basically they help to create a fresh set of governing limit.

.Each test method can call the start test and stop test only once.

3) What is the use of seeAllData=true ? 

==>seeAllData=true

If we are defining a test class with @isTest(SeeAllData=true) then we can access data in test
class from the database under all method present in the test class. Under this case
annotating a method with @isTest(SeeAllData=false) would be ignored and you can access
database data inside this method as well.

Let's understand with an example.

@isTest(SeeAllData=true)

public class testclassexample {

static testmethod void testMethodFirst() {

contact obj = [SELECT Id, Name from contact where name='test' LIMIT 1];
//Accessing contact from database

@isTest(SeeAllData=false)

static testmethod void testMethodFirst() {

contact obj1 = [SELECT Id, Name from contact where name='test' LIMIT 1];

//Accessing contact from database although @isTest(SeeAllData=false) is applied for


method but it will get ignored as test class is having @isTest(SeeAllData=true).

4) What is the use of seeAllData=false ? 

==>@isTest(SeeAllData=false)

If we are defining a test class with @isTest(SeeAllData=false) then we cannot access data in
test class from the database under all method present in the test class. Under this case
annotating a method with @isTest(SeeAllData=true) would not be ignored and you can
access database data inside this method.

Let's understand with an example.


@isTest(SeeAllData=false)

public class testclassexample {

static testmethod void testMethodFirst() {

//You cannot access like this now.

contact obj = [SELECT Id, Name from contact where name='test' LIMIT 1];

//You need to create test data

Contact obj=new contact();

obj.name='test';

insert obj;

@isTest(SeeAllData=true)

static testmethod void testMethodFirst() {

contact obj1 = [SELECT Id, Name from contact where name='test' LIMIT 1];

//Accessing contact from database although @isTest(SeeAllData=false) is applied for class


but it will get ignored.

}
}

5) What are test class best practices? 

1) We should always considered doing testing with bulk records.

2) We Should test "test cases" for both positive and negative test scenario.

3) Avoid using (SeeAllData=true) in test class because it might happen that the test class
pass in sandbox but fails in production if data is not present in production.

4) Avoid using hardcoded is's in  test class.

6) What is @testSetup? 

Method that are annotated with @testSetup are used to create test data and we can this test
data inside every method of the test class. The testSetup method is executed first in any test
class before other methods.

7) Let say i have a test class in which i have created a testSetup method in which
i am creating a contact record. Let say i have two test method inside my test
class which is accessing this contact record. If i access this contact record in
testmethod1() and made a update to the contact record from testSetup method
and now i am accessing this contact in testmethod2(), so will i get the updated
contact record or the original unmodified contact record in testmethod2()?
testMethod2() will  gets access to the original unmodified state of  record, this is because
changes are rolled back after each test method finishes execution.

8) If the test class is having access to organization data using


@isTest(SeeAllData=true) annotation, will the test class be able to support
@testSetup method?

@testSetup method are not supported in this case.

9) How many @testSetup method are supported inside a test class?

One test setup method per test class.

10) Why is @TestVisible annotation used in test class?

Using @TestVisible annotation before variable or methods or inner classes inside apex class
allows test class to access them. This annotation does not change the visibility of variable or
methods or inner classes if accessed by non-test class.

Apex class:

public class apexClassExample{


@TestVisible private static integer rollNo=1;

Test class: 

@isTest

public class apexClassExampleTest{

static testmethod void methodName()

    Integer rollNo=apexClassExample.rollNo;

11) What is System.runAs() in test class?


Test class runs in system mode, System.runAs() allow us to run the test in context of current
user where user 's record sharing is taken into account. User permission or field level
permission are not taken into account.

12) What is the use of test.isrunningtest()? 

Sometimes it may happen that in test class you are not able to satisfy certain condition in
apex class

so under this case, we can bypass this condition by writing test.isrunningtest() in apex class.

Syntax:

In Apex under condition,

if(a=3 || test.isrunningtest())

You might also like