Apex Testing Interview Questions: Coverage and Mocks (60+ Q&A)

Apex Testing Interview Questions with answers on test classes, coverage, test data, mocks, the Stub API and the scenarios interviewers ask most often.

Updated 20 min read
Apex Testing Interview Questions featured image with sample question cards

Apex Testing Interview Questions get asked in every developer interview, because every deployment depends on tests passing. This post collects the questions that come up most, with answers short enough to say in a conversation.

Last reviewed for the Winter ’27 release (November 2026).

The questions group into five areas. Test basics and coverage, test data, callouts and mocks, the Stub API, and scenario questions where something is failing and you have to explain why.

Apex Testing Interview Questions diagram showing setup, execution, assertions and rollback

Caption: A test gets its own data and its own fresh limits, and nothing it creates survives the run.

What Apex Testing Interview Questions Cover

Apex Testing Interview Questions test whether you write tests because they are required or because they catch bugs. Interviewers can tell the difference within two answers.

Apex Testing Interview Questions start from one idea. A test class is ordinary Apex marked as test code. It creates its own data, runs the code under test, and asserts the result. Nothing it inserts is saved when the run finishes.

Think of it like a rehearsal on a stage set. Mocking your own classes is covered in the post on the Apex Stub API, and HTTP mocking in callout mocks. Everything looks real while you are on it, and the set is taken down afterwards.

How a Test Class Is Structured

PieceWhat it does
IsTest annotationMarks the class or method as test code
TestSetup methodCreates data once for every test in the class
Test.startTestResets limit counters before the code under test
Test.stopTestEnds that block and completes asynchronous work
Assert methodsCheck the result, which is the actual point
System.runAsRuns a block as a different user

Apex Testing Interview Questions often focus here. Those two methods around the code under test matter more than people expect. Without them, the limits consumed by your data setup count against the code you are testing.

@IsTest
private class CourseServiceTest {

    @TestSetup
    static void makeData() {
        insert new Course__c(Name = 'Apex Basics', Fee__c = 4500, Level__c = 'Beginner');
    }

    @IsTest
    static void appliesOnlineDiscount() {
        Course__c c = [SELECT Id, Fee__c FROM Course__c LIMIT 1];

        Test.startTest();
        new CourseService().moveOnline(c.Id);
        Test.stopTest();

        Course__c after = [SELECT Fee__c, Is_Online__c FROM Course__c WHERE Id = :c.Id];
        Assert.areEqual(3825, after.Fee__c, 'Online courses get 15 percent off');
        Assert.isTrue(after.Is_Online__c, 'The course should be marked online');
    }
}

Notice the assertion messages, which Apex Testing Interview Questions tend to probe. An interviewer will often ask why they matter, and the answer is that a failing test should say what was expected without anyone reading the code.

Coverage and What It Really Means

Apex Testing Interview Questions comparison of real test data and mocks

Caption: Mocks test logic quickly, and real data tests the parts that only break with records present.

RuleThe number
Minimum coverage to deploy75 percent of Apex lines
Coverage per triggerEvery trigger needs some coverage
Test methods counted in coverageNo, test code is excluded
Asserts required by the platformNone, which is the real problem

Apex Testing Interview Questions return to that gap again and again.

That last row is the one to talk about. The platform checks lines executed, not whether anything was verified, so coverage with no assertions proves nothing. The post on test class basics covers the mechanics.

Apex Testing Interview Questions on the Basics

Q1: What annotation marks a test class?

The @IsTest annotation, on the class and on each test method.

Example: @IsTest private class CourseServiceTest { @IsTest static void appliesDiscount() { … } } Test classes do not count toward the org’s Apex code size limit.

Q2: Does test code count towards coverage?

No. Test classes are excluded from coverage, and they do not need coverage themselves.

Coverage measures how many lines of your real classes and triggers ran while the tests executed.

Q3: What coverage do you need to deploy?

At least 75 percent of Apex lines across the org, and every trigger needs some coverage.

Treat 75 as the floor, not the goal. Good teams aim for 85 to 90 percent with real assertions, so new code does not drop the org below the line.

Interview tip: add “75 is the floor, assertions are the goal”. It shows quality thinking.

Q4: Does every trigger need coverage?

Yes. Every trigger needs at least some coverage, or the deployment fails.

Even a one line trigger that calls a handler needs a test that fires it, for example by inserting one record of that object.

Follow-up you may get: Do classes need individual minimum coverage? No, but each trigger needs some.

Q5: Can a test class be private?

Yes, and private is the normal choice, because nothing outside the class needs to call it.

Use public only for shared test utilities, like a test data factory that many test classes call.

Q6: What does Test.startTest do?

It starts a fresh set of governor limits for the code after it, so setup work does not count against the code under test.

Example: insert 200 records before startTest, then call the service; the service gets its own 100 queries.

Interview tip: say both jobs of startTest: fresh limits and marking where async work begins.

Q7: What does Test.stopTest do?

It ends the fresh limit block and forces queued asynchronous work, like queueables, future methods and batches, to run.

Anything enqueued between startTest and stopTest finishes at stopTest, so you can assert its results right after.

Follow-up you may get: Do chained queueables run in tests? Only the first job; chaining is not run in tests.

Q8: Why does that matter for a queueable?

Because the job executes only when stopTest is reached, so assertions must come after it.

Example: Test.startTest(); System.enqueueJob(new SyncJob()); Test.stopTest(); then query the records and assert.

Q9: How many times can you call startTest in one method?

Once per test method.

Calling it a second time throws an error. If you need two separate measured blocks, write two test methods.

Q10: What does TestSetup give you?

Records created once per test class, and each test method starts with a fresh copy of them.

Changes one test makes are rolled back before the next one runs, so tests stay independent. It also makes the suite faster than creating the same data in every method.

Interview tip: mention that each method gets a fresh copy, so tests stay independent.

Q11: When can you not use TestSetup?

When the class uses @IsTest(SeeAllData=true).

Test setup methods and SeeAllData do not work together, which is one more reason to avoid SeeAllData.

Q12: What does seeAllData true do?

It lets the test see existing org data, not only what the test created.

By default, tests see only their own records plus some setup data like users and profiles.

Follow-up you may get: Can SeeAllData be set on one method? Yes, but it is still best avoided.

Q13: Why avoid it?

Because the test then depends on whatever data the org has, so it passes in one org and fails in another.

A record someone deletes in production can break a deployment months later. Create your own data instead.

Interview tip: SeeAllData is almost always a wrong answer. Say why in one line.

Q14: Which objects are visible even without seeAllData?

Setup and metadata style objects, like User, Profile, RecordType, Organization and custom metadata records.

So a test can query the System Administrator profile or a record type without SeeAllData.

Q15: How do you test as a different user?

Wrap the code in System.runAs with a user record you created in the test.

Example: User u = TestFactory.createUser(‘Standard User’); System.runAs(u) { … } Everything inside runs as that user.

Q16: Why is runAs useful?

It proves sharing and permission behaviour instead of assuming it.

Example: run as a sales user and assert they cannot see another region’s accounts. runAs enforces record sharing; for field access, the code must use user mode.

Interview tip: mention that runAs enforces record sharing but not field permissions.

Q17: Does runAs bypass limits?

No. It changes only the user context, not the governor limits.

It also lets you avoid mixed DML errors in tests, by inserting the user inside a runAs block.

Q18: What is the difference between Assert and System.assert?

The Assert class is the newer form, with clearer method names. Both check the same things.

Assert classOlder System methodChecks
Assert.areEqual(expected, actual)System.assertEqualsTwo values match
Assert.areNotEqualSystem.assertNotEqualsTwo values differ
Assert.isTrue(condition)System.assertA condition is true
Assert.isNull / isNotNullSystem.assert(x == null)A value is or is not null
Assert.fail(message)NoneAlways fails, for code that should not be reached

Q19: Why write an assertion message?

So a failure explains itself without anyone opening the code.

Example: Assert.areEqual(10, c.Seats__c, ‘Online courses should default to 10 seats’); The message shows in the test result.

Follow-up you may get: Do assertion messages cost anything? No, they only show on failure.

Q20: How many assertions should a test have?

Enough to prove the behaviour, often one to three, each checking a different thing.

Assert the main result, plus a side effect if it matters, like a task being created. Ten assertions in one test usually mean the test should be split.

Q21: What is a negative test?

A test that proves the code rejects bad input, usually by checking for an expected error.

Example: insert a course with a negative fee and assert the save fails with the right validation message.

Interview tip: give an example of a negative test from a real project. It sounds more credible.

Q22: How do you assert that an exception was thrown?

Run the code in a try block, call Assert.fail() right after it, and check the message in the catch.

Example: try { svc.enroll(null); Assert.fail(‘Expected an exception’); } catch (EnrollmentException e) { Assert.isTrue(e.getMessage().contains(‘required’)); }

Q23: What is the difference between unit tests and integration tests in Salesforce?

A unit test checks one class or method in isolation, often with stubs, and runs very fast. An integration style test runs real DML through triggers, flows and validation rules to prove the pieces work together. A healthy suite has many unit tests and fewer integration tests.

Q24: How do you test a private method?

Usually through the public method that calls it, which tests real behaviour. If a private method is complex enough to need its own test, mark it @TestVisible so the test class can call it directly.

Q25: Is a test with no assertion useful?

Only for coverage, which is why it is the clearest sign of coverage driven testing.

A test that only runs lines without checking results gives false confidence. Every test should assert at least one real outcome.

Apex Testing Interview Questions on Test Data

Q26: Where should test data come from?

From the test itself, usually through a shared test data factory class.

The factory creates valid records with all required fields, so tests can say only what matters to them.

Q27: Why use a factory rather than inline inserts?

One place to change when a required field or validation rule is added, instead of forty test methods.

It also keeps tests short and readable: TestFactory.createCourses(200, true) says exactly what the test needs.

Follow-up you may get: Should the factory be a test class? Yes, mark it @IsTest so it does not count toward code size.

Q28: Should a factory insert records or return them?

Returning unsaved records is more flexible, with a separate method or flag that inserts when needed.

The test can then change fields before the insert, like setting an invalid value for a negative test.

Q29: How do you test bulk behaviour?

Create 200 records in one DML statement and assert the outcome for all of them, not just the first.

Loop over the queried results and check each one, so a bug that only affects record 150 is caught.

Interview tip: say you assert every record, not just the first. Small detail, big signal.

Q30: Why 200 specifically?

Because 200 is the trigger chunk size, so it matches how data loads and integrations behave.

Testing with 201 or more also covers the case where a second chunk runs in the same transaction.

Q31: How do you handle required fields you do not care about?

Set them in the factory with sensible defaults, so each test states only what matters.

Example: the factory always fills Name, Start_Date__c and Level__c, and a test about fees only sets Fee__c.

Q32: What is the problem with hard coded ids in tests?

IDs differ between orgs, so the record does not exist where the test runs and it fails on deployment.

Create the record in the test, or look it up by a stable value like DeveloperName.

Q33: How do you get a record type id safely?

Look it up by developer name through a describe call, not a hard coded ID.

Example: Id rt = Schema.SObjectType.Course__c.getRecordTypeInfosByDeveloperName().get(‘Online’).getRecordTypeId(); It needs no SOQL.

Q34: Can a test insert a user?

Yes, and that is the normal way to get a user for runAs.

Use a unique username, query the profile by name, and insert the user inside a runAs block to avoid mixed DML errors.

Q35: How do you test custom settings?

Insert the setting record in the test, because org data is not visible by default.

Example: insert new Feature_Flags__c(SetupOwnerId = UserInfo.getOrganizationId(), Enable_Sync__c = true); then run the code.

Q36: How do you test custom metadata?

Custom metadata records are visible to tests, so you can query them, and inject values where behaviour must vary.

You cannot insert custom metadata with DML, so for different values per test, put the reading behind a class you can stub or pass the values in.

Follow-up you may get: Can tests create custom metadata records? Not with DML; build them in memory or deploy test records.

Q37: Why is data setup often the slowest part of a suite?

Because every insert fires triggers, validation rules, flows and other automation.

A test that inserts 500 records through five triggers may spend most of its time in setup, not in the code it tests.

Q38: How do you test code that uses Date.today()?

Pass the date into the method, or read it through a small class you can stub, so the test can set any date. A hard coded Date.today() makes tests that depend on the calendar and fail on weekends or month ends.

Q39: How do you test record type specific logic?

Get the record type ID by developer name in the test, create records with that RecordTypeId, and assert the behaviour. Create one record of each relevant type so each branch is covered.

Q40: How do you speed that up?

Stub the dependencies for logic tests and keep real data for integration style tests.

Example: a pricing service test passes a stubbed selector that returns three in memory courses, so it runs in milliseconds with no inserts at all.

Apex Testing Interview Questions on Callouts and Mocks

Q41: Can a test make a real callout?

No. Tests cannot call outside services, so the response must be mocked.

A test that tries a real callout fails with an error. Mocks also make tests fast and repeatable.

Interview tip: name the error: “Methods defined as TestMethod do not support Web service callouts”.

Q42: Which interface mocks an HTTP callout?

HttpCalloutMock, which returns your fake HttpResponse from its respond method.

Example: public class WeatherMock implements HttpCalloutMock { public HttpResponse respond(HttpRequest req) { HttpResponse res = new HttpResponse(); res.setStatusCode(200); res.setBody(‘{“temp”:31}’); return res; } }

Q43: How do you register the mock?

With Test.setMock, passing the interface type and your mock instance.

Example: Test.setMock(HttpCalloutMock.class, new WeatherMock()); Call it before the code that makes the callout.

Q44: How do you test a failure response?

Return a 500 status from the mock and assert how your code handles it.

Check that it logs the error, retries or shows a friendly message, whatever your design says. Error paths are where real bugs hide.

Q45: How do you test a timeout?

Throw a CalloutException from the mock and assert the handling.

Example: inside respond, throw new CalloutException(‘Read timed out’); then assert the code caught it and recorded a failure.

Q46: Can one mock serve several endpoints?

Yes. Branch on the request endpoint or method inside the respond method.

Example: if (req.getEndpoint().contains(‘/token’)) return a token response, else return the data response. MultiStaticResourceCalloutMock can also map endpoints to static resources.

Follow-up you may get: What is StaticResourceCalloutMock? A mock that returns a static resource file as the response body.

Q47: What mocks a web service callout?

WebServiceMock, the SOAP equivalent, used for classes generated from a WSDL.

Its doInvoke method puts the fake response into the response map, and you register it with Test.setMock(WebServiceMock.class, new MyMock()).

Q48: How do you mock a continuation?

Use Test.setContinuationResponse to set the fake response, and Test.invokeContinuationMethod to run the callback.

That lets you test a Lightning or Visualforce controller that uses Continuation without waiting on a real service.

Q49: Does a mocked callout count against callout limits?

It counts as a callout in the transaction, so the 100 callout limit still applies.

A test with 200 records that makes one callout per record would fail, which shows the same bug production would have.

Interview tip: connect mocks to bulk testing. Interviewers rarely hear it.

Q50: What is the Stub API for?

Replacing one of your own classes with a fake at run time, so the test runs no DML and no callouts.

ToolReplacesTypical use
HttpCalloutMockHTTP calloutsREST integrations
WebServiceMockSOAP calloutsWSDL generated classes
Stub API (StubProvider)Your own Apex classesFake a service or selector in a unit test
Test.setFixedSearchResultsSOSL resultsSearch methods

Q51: Which interface does a stub provider implement?

The System.StubProvider interface, with a handleMethodCall method.

handleMethodCall gets the method name, parameter types and values, and returns whatever fake result the test needs.

Q52: How do you create the stub?

With Test.createStub, passing the class type and your provider.

Example: CourseSelector sel = (CourseSelector) Test.createStub(CourseSelector.class, new CourseSelectorStub()); then pass sel into the service under test.

Follow-up you may get: Can you stub an interface? Yes, Test.createStub works with interfaces and classes.

Q53: Can you stub a static method?

No. Only instance methods can be stubbed, not static ones.

Private methods and some system types cannot be stubbed either.

Q54: What does that imply for class design?

Write services as instance classes and accept their dependencies in a constructor.

Example: new EnrollmentService(new CourseSelector()) in production, and new EnrollmentService(stubSelector) in tests.

Interview tip: mention dependency injection by name. It shows design maturity.

Q55: How do you make a stub throw?

Throw the exception from inside the provider when that method name is called.

Example: if (methodName == ‘getCourses’) throw new QueryException(‘Simulated failure’); The service’s error path then runs.

Q56: Why is that valuable?

Error paths are very hard to reach with real data and easy with a stub.

Making a real query fail or a real service time out on demand is almost impossible in a test, but a stub can do it in one line.

Q57: How do you assert a method was called?

Record the method names in the provider and assert on that list afterwards.

Example: the stub adds each methodName to a public List<String> calls, and the test asserts calls.contains(‘sendEmail’).

Q58: How do you test a platform event trigger?

Publish the event in the test, then call Test.getEventBus().deliver() or Test.stopTest() to deliver it. Then assert on the records the subscriber trigger created or changed.

Q59: How do you test a batch job?

Insert test records, call Database.executeBatch between Test.startTest and Test.stopTest, then assert the results. Only one execute runs in a test, so keep the test data within one batch size.

Q60: When should you still use real data instead?

For triggers, validation rules, sharing and query behaviour.

Use real records whenever the behaviour depends on the database or the platform, and stubs when you test your own logic in isolation.

Scenario Based Apex Testing Interview Questions

Q61: Scenario: a test passes locally and fails on deployment. What do you check first?

Hard coded IDs, SeeAllData, or a dependency on org data that does not exist in the target org.

Also check required fields or validation rules that exist only in production, and users or profiles the test assumes.

Follow-up you may get: How do you run tests before deploying? sf project deploy validate with RunLocalTests.

Q62: Scenario: coverage is 80 percent but a bug reached production. How?

Lines ran without assertions, so nothing checked that the result was right.

Coverage only shows which lines executed. Add assertions on the actual results, plus negative and bulk tests.

Q63: Scenario: a queueable assertion always fails. What is wrong?

The assertion runs before Test.stopTest, so the job has not run yet.

Move the assertion after stopTest, and query the records again so you read the new values.

Q64: Scenario: one validation rule change breaks 30 tests. What does that tell you?

The suite depends on real data and automation everywhere, so logic tests should use stubs.

Keep a few tests that run the real save with triggers and rules, and test the business logic with stubbed selectors.

Interview tip: frame it as brittle tests, and propose stubs plus a data factory.

Q65: Scenario: the suite takes 20 minutes. What do you propose?

Split the work: stubbed unit tests for most logic, and fewer data tests for triggers and integration paths.

Also share setup through @TestSetup, cut unneeded records, and run only related tests on pull requests with full runs before releases.

Q66: Scenario: a test fails only when run with the whole suite. Why?

Usually because tests running in parallel touch the same records or unique values, or because the test depends on org data another test changes.

Static variables reset between test methods, so look for UNABLE_TO_LOCK_ROW errors, duplicate unique fields or shared custom settings. Unique values per test, or disabling parallel test runs, usually fixes it.

Q67: Scenario: a trigger test passes with one record and production fails at volume. What was missed?

A bulk test with 200 records.

With one record, a query inside a loop runs once and passes. With 200, it runs 200 times and fails, which only a bulk test catches.

Q68: Scenario: a callout test fails with an unauthorized endpoint error. What happened?

No mock was registered, so the code tried a real callout.

Call Test.setMock before the code runs. A test that hits a real endpoint is never allowed in Apex.

Q69: Scenario: you inherit a class of static methods that cannot be tested well. What now?

Refactor it into an instance service, so dependencies can be passed in and stubbed.

Keep the old static methods as thin wrappers that call the new service, so existing callers keep working while tests get better.

Q70: Scenario: an interviewer asks how you would raise quality without raising coverage. What do you say?

Add assertions, negative tests and bulk tests to the tests that already exist.

Also run tests as real user profiles with System.runAs. Quality improves even if the coverage number stays the same.

Q71: Scenario: a test creates a user and fails on a duplicate username. How do you fix it?

Generate a unique username, usually with a timestamp or random suffix.

Example: username = ‘test’ + DateTime.now().getTime() + ‘@example.com.test’; Usernames must be unique across all Salesforce orgs, not just yours.

Q72: Scenario: a test fails because a validation rule needs a field the test does not set. What do you change?

Add the field to the test data factory’s defaults, so every test that creates the record gets a valid value. That fixes all affected tests in one place.

Q73: Scenario: a test needs a queue to own records. How do you set it up?

Insert a Group with Type ‘Queue’ and a QueueSobject linking it to the object, inside a System.runAs block to avoid mixed DML. Then insert records with OwnerId set to the queue’s ID.

Q74: Scenario: a scheduled job needs testing. How?

Call System.schedule inside startTest and stopTest, then assert the work it performed.

Example: Test.startTest(); System.schedule(‘Nightly’, ‘0 0 1 * * ?’, new NightlyJob()); Test.stopTest(); then assert what the job’s execute method changed.

Common Mistakes Candidates Make

  • Talking about 75 percent coverage as if it were the goal, which Apex Testing Interview Questions are built to catch
  • Writing tests with no assertions and calling them done
  • Using seeAllData true to avoid creating data
  • Testing with one record when production sends 200
  • Forgetting that assertions must come after stopTest for asynchronous work
  • Not knowing that callouts must be mocked

Best Practices to Mention in an Interview

  • One shared test data factory, so a new required field is one change
  • An assertion with a message in every test
  • A bulk test with 200 records for every trigger
  • A negative test for every rule the code enforces
  • Stubs for logic, real data for the data layer
  • Mocks for every callout, including the failure cases
  • Unique values for anything the platform requires to be unique

Official Resources

Quick Recap

  • Apex Testing Interview Questions look for assertions, not coverage numbers
  • Wrap the code under test in startTest and stopTest
  • Create data in the test, through a factory, and avoid seeAllData
  • Mock every callout and stub your own services for logic tests
  • Test 200 records for anything a trigger touches
  • Negative tests prove the rules your code enforces

What Is Next

Next, read Asynchronous Apex Interview Questions: Future to Batch (60+ Q&A).