# How to Test SMS OTP Codes End to End with Real Phone Numbers

Check that an OTP SMS is actually delivered, read real verification codes in Playwright, Cypress or Selenium, and run SMS two-factor tests in CI without flaky shared phones.

A six-digit code by text message is the easiest part of signing in for a person and the hardest part for a test suite. The browser half is ordinary automation. The other half happens on a phone: a carrier has to deliver the message, somebody has to read it, and the code expires in a few minutes. So most suites mock the SMS client, accept a fixed code in staging, and trust that production texts turn up.

This guide replaces that trust with a test. It covers how to check that an OTP SMS really arrives, where to get a phone number a test can read, how to automate the sign-in in Playwright, Cypress or Selenium, which tools cover SMS, email and authenticator codes, and how to run it all in CI without tests reading each other's codes. The examples use MailSlurp, an API that gives tests real phone numbers and email inboxes and lets them wait for the next message, and a [runnable Playwright project](https://github.com/mailslurp/examples/tree/master/playwright-sms-2fa-real-number) you can clone.

## Quick answers

**How do I check that an OTP SMS is actually delivered?** In production, track your SMS provider's delivery receipts and compare codes sent with codes entered. Neither shows the text a person received, so add a real-number check: send a code to a phone number your test controls, read the text through an API, and check its sender, wording, code and arrival time. [How to check delivery](#check-that-an-otp-sms-is-actually-delivered)

**How do I receive a real SMS verification code in a test?** Give the test a private, non-VoIP phone number on a real carrier that it can read programmatically, such as a MailSlurp number. Note the time, trigger the code, then call `waitForSms` for that number with that time and a timeout. It returns as soon as the text arrives, and the test types the code in. [Code example](#receive-a-real-sms-code-in-a-test)

**How can I test SMS OTP codes in automated end-to-end tests?** Use two layers. Fast tests with a simulated SMS sender run on every pull request and cover right, wrong and reused codes. A real-number test receives a real text before each release and signs in with it. [Playwright walkthrough](#automate-an-sms-otp-sign-in-in-playwright)

**How do I test SMS and email MFA in Cypress or Selenium?** The steps are the same in any test runner: request the code in the browser, wait for the message with the MailSlurp client for your language, extract the code and submit it. [Other test runners](#use-the-same-pattern-in-cypress-selenium-and-other-runners)

**What tools test OTP, MFA and 2FA login flows end to end?** Pair a browser runner such as Playwright, Cypress or Selenium with a source for each kind of code: real phone numbers for SMS, test inboxes for email, and a TOTP generator for authenticator apps. MailSlurp provides all three through one API. [OTP testing tools](#otp-mfa-and-2fa-testing-tools)

**How do I run SMS tests in GitHub Actions or another CI pipeline?** Run the simulated suite on every build, and the real-number test against your own sign-up page nightly or before a release, with the API key stored as a CI secret. Give each parallel job its own number by leasing one from a phone pool. [CI setup](#run-sms-otp-tests-in-ci-without-flaky-shared-numbers)

**Where can I get a real phone number for automated OTP tests?** Rent a private number for testing rather than using a public receive-SMS website. MailSlurp numbers are available in ten countries as local, mobile or toll-free numbers, with a non-VoIP filter in the US, UK and Australia. [Choose a number](#choose-a-test-number-your-sms-provider-will-deliver-to)

## Why SMS codes are hard to test

Every obvious workaround fails in its own way:

- **A physical phone doesn't fit in a build.** Someone has to hold it, unlock it and type the code. Each device has one number, and none of them run at 3 a.m. inside a CI container.
- **Provider sandboxes don't send anything.** Twilio's test credentials validate a request and return a message object, but Twilio [doesn't connect to real phone numbers](https://www.twilio.com/docs/iam/test-credentials) with them and status callbacks never fire. Firebase's fictional phone numbers accept a fixed code and send no SMS. Both check your code path. Neither tells you anything about the text.
- **Public receive-SMS websites are, well, public.** Anyone can read the codes, the numbers are shared with strangers, and many services refuse them. A test that depends on one is both flaky and leaky.
- **Shared numbers cause races.** When two tests ask for codes on the same number at once, each can read the other's code. The suite then passes or fails depending on timing.
- **Codes expire.** Five minutes is common. A test that sleeps for a fixed time either wastes most of it or misses the code.

MailSlurp handles that last stretch between your SMS provider and your test:

- **Real numbers you control.** Rent numbers in the dashboard or through the API, and read every text they receive.
- **Wait-for methods.** `waitForSms` and `waitForLatestSms` wait on the server for a message that arrived after a given time and matches its sender or body, so tests need no sleep or polling loop.
- **Phone pools.** Parallel jobs lease different numbers from a pool and release them afterwards, so no two tests share a number at the same time.
- **The right kind of number.** Choose the country, the number type and, where offered, a non-VoIP line, so your provider routes the text the way it would for a customer.
- **Email and authenticator codes too.** The same API creates inboxes for email codes and virtual TOTP devices for authenticator apps.

## Check that an OTP SMS is actually delivered

SMS delivery testing answers a different question from your provider's dashboard. The dashboard reports what the provider knows: the API accepted the request, the message was queued, passed to a carrier and, sometimes, delivered. A delivered status is a receipt from the carrier network. Some carriers and countries don't return one, and a phone can still file the text under unknown senders. None of these statuses shows the text a person actually received, which is where most OTP bugs live:

- the wrong sender, such as a test number or a sender ID that a country doesn't allow;
- a template change that dropped the code or split it across two lines;
- a route that delivers in 90 seconds when the code expires in 60;
- a number format, such as a missing country code, that sends the code somewhere else entirely.

### Watch delivery in production

Three signals, together, tell you most of what's happening to real users:

1. **Delivery receipts.** Store the provider's message ID with each code request and record its status callbacks: queued, sent, delivered or failed, with the error code.
2. **Verification rate.** Compare codes sent with codes entered, by country and by carrier where you have it. A route that silently drops messages shows up here as a falling rate, even while receipts say delivered.
3. **Latency.** Measure the time from request to delivered receipt, and from request to code entered. Slow routes cause expired codes and abandoned sign-ins before they cause outright failures.

### Check one message by hand

Before writing any code, register a test account with a MailSlurp number and request a code from your app. The text appears in the MailSlurp dashboard with its sender and arrival time. Check four things:

1. The sender is the short code, long code, toll-free number or sender ID your users will see.
2. The message has your app's wording and exactly one code.
3. The code arrived well within its expiry time.
4. The code signs you in once, and a second attempt with it is refused.

### Then check it on a schedule

The real-number test in the next section repeats those checks automatically. Run it before each release, and on a schedule against your live sign-up with a number in each country you serve: it fails if no text arrives within 60 seconds, extracts the code only from a message with the expected wording, signs in with it, and records how long delivery took.

## Receive a real SMS code in a test

The fastest way to see this working is MailSlurp's [SMS playground](https://playground-sms.mailslurp.com), a demo app whose sign-up texts a real verification code to the phone number you register. Its accounts live in an AWS Cognito user pool, and the phone number is the username. The [example project](https://github.com/mailslurp/examples/tree/master/playwright-sms-2fa-real-number) signs up to it with a MailSlurp number, so you can run a real SMS test without your own app or SMS provider account. To test your own app, swap in your sign-up page; the MailSlurp calls stay the same.



![The SMS playground's Testable Sign Up Form with a +1 dial code, a sample phone number and a password filled in, above a Create account button](/_astro/playground-sign-up-form.DeYiflTt_Z17fv9N.webp)

The playground's sign-up form, filled in with a sample number. The test enters a MailSlurp number here.



The test imports the MailSlurp client, which reads the API key from the environment:



```typescript
import { test } from "@playwright/test";
import { MailSlurp, SmsMatchOptionFieldEnum, SmsMatchOptionShouldEnum } from "mailslurp-client";
import { confirmAndSignIn, deleteSignedInUser, extractCode, findTestPhone, removeLeftoverUser, signUp } from "./playground";

const mailslurp = new MailSlurp({ apiKey: process.env.MAILSLURP_API_KEY ?? "" });
```



It picks the number to sign up with: the one in `MAILSLURP_PHONE_ID` if you set it, otherwise the first US number in the account:



```typescript
// Use MAILSLURP_PHONE_ID if set, otherwise the first US number in the account.
export async function findTestPhone(mailslurp: MailSlurp): Promise<{ id: string; phoneNumber: string }> {
  const pinned = process.env.MAILSLURP_PHONE_ID?.trim();
  if (pinned) return mailslurp.phoneController.getPhoneNumber({ phoneNumberId: pinned });
  const { content } = await mailslurp.phoneController.getPhoneNumbers({
    phoneCountry: GetPhoneNumbersPhoneCountryEnum.US,
  });
  const phone: PhoneNumberProjection | undefined = content?.[0];
  if (!phone) throw new Error("This test needs a US phone number in your MailSlurp account.");
  return phone;
}
```



Signing up is ordinary Playwright. The form wants the number without its country code, because the dial code select supplies the +1:



```typescript
export async function signUp(page: Page, phoneNumber: string) {
  await page.goto("/");
  await page.click('[data-test="sign-in-create-account-link"]');
  // The form takes the number without its +1 country code, which the dial code select provides.
  await page.fill('[data-test="phone-number-input"]', phoneNumber.replace(/^\+1/, ""));
  await page.fill('[data-test="sign-up-non-phone-number-input"]', PLAYGROUND_PASSWORD);
  await page.click('[data-test="sign-up-create-account-button"]');
  await expect(page.locator('[data-test="confirm-sign-up-confirmation-code-input"]')).toBeVisible();
}
```



Now the test itself. It records the time, signs up, and waits for the first text on that number that arrived after that time and contains the playground's wording:



```typescript
test("signs up with the SMS code sent to a real phone number", async ({ page }, testInfo) => {
  const phone = await findTestPhone(mailslurp);
  await removeLeftoverUser(page, phone.phoneNumber);

  // Count only messages that arrive after this test asks for a code.
  const since = new Date();
  await signUp(page, phone.phoneNumber);

  const [sms] = await mailslurp.waitController.waitForSms({
    waitForSmsConditions: {
      phoneNumberId: phone.id,
      since,
      count: 1,
      timeout: 60_000,
      matches: [{ field: SmsMatchOptionFieldEnum.BODY, should: SmsMatchOptionShouldEnum.CONTAIN, value: "demo-sms verification code" }],
    },
  });
  const seconds = (new Date(sms.createdAt).getTime() - since.getTime()) / 1000;
  testInfo.annotations.push({ type: "delivery", description: `SMS received ${seconds.toFixed(1)} s after sign-up` });

  await confirmAndSignIn(page, phone.phoneNumber, extractCode(sms.body));

  // Leave the number free to sign up again on the next run.
  await deleteSignedInUser(page);
});
```



Each condition earns its place:

- **`since`** ignores codes from earlier runs. Taking the time before the code is requested is what makes a rerun safe.
- **`matches`** on the body skips anything else the number receives.
- **`timeout: 60_000`** turns "the text never came" into a clear failure.
- **The annotation** adds the measured delivery time to the Playwright report, so a slow route shows up before your users notice it.

The code is pulled out by a helper that is deliberately fussy. It fails unless the message carries the playground's wording and holds exactly one six-digit code, so a template that accidentally includes two numbers fails the test instead of signing in by luck:



```typescript
// Exactly one six-digit code from the playground's verification text.
export function extractCode(body: string): string {
  if (!body.includes("demo-sms verification code")) throw new Error("The SMS is not a playground code.");
  const codes = body.match(/(?<!\d)\d{6}(?!\d)/g) ?? [];
  if (codes.length !== 1) throw new Error(`Expected one six-digit code, found ${codes.length}.`);
  return codes[0];
}
```



The test then confirms the account with the code and signs in with the same number and password:



```typescript
export async function confirmAndSignIn(page: Page, phoneNumber: string, code: string) {
  await page.fill('[data-test="confirm-sign-up-confirmation-code-input"]', code);
  await page.click('[data-test="confirm-sign-up-confirm-button"]');
  await signIn(page, phoneNumber);
  await expect(page.locator('[data-test="greetings-nav"]')).toBeVisible();
}
```



### Clean up so the number works next time

The playground allows one account per phone number, so a second run with the same number would fail at sign-up. The last step deletes the user it just created, using the session it signed in with and Cognito's `DeleteUser` call:



```typescript
// Delete the signed-in playground user with Cognito's DeleteUser call, so the same phone number can
// sign up again on the next run. The access token is the one the app stored when it signed in.
export async function deleteSignedInUser(page: Page) {
  const accessToken = await page.evaluate(() => {
    const key = Object.keys(localStorage).find((k) => k.startsWith("CognitoIdentityServiceProvider.") && k.endsWith(".accessToken"));
    return key ? localStorage.getItem(key) : null;
  });
  if (!accessToken) throw new Error("No signed-in playground session to delete.");
  // The token's issuer names the Cognito region, for example https://cognito-idp.us-west-2.amazonaws.com/<pool>.
  const { iss } = JSON.parse(Buffer.from(accessToken.split(".")[1], "base64url").toString());
  const response = await page.request.post(`${new URL(iss).origin}/`, {
    headers: {
      "content-type": "application/x-amz-json-1.1",
      "x-amz-target": "AWSCognitoIdentityProviderService.DeleteUser",
    },
    data: JSON.stringify({ AccessToken: accessToken }),
  });
  expect(response.ok(), `DeleteUser failed: ${await response.text()}`).toBeTruthy();
}
```



If an earlier run stopped before that step, the test starts by signing in with the same password and deleting the leftover user. Your own app needs the same kind of reset: an admin endpoint or database cleanup that removes the test account, or a fresh number for every run.

## Automate an SMS OTP sign-in in Playwright

Sending a real text on every pull request would be slow and would cost money. The example therefore has two suites: a local one that runs everywhere in about a second, and the real-number test above for releases.

### Run the example

You need Node.js 22.12 or later. Clone the [examples repository](https://github.com/mailslurp/examples) and run the local suite, which needs no credentials or network access:

```bash
cd examples/playwright-sms-2fa-real-number
npm ci
npx playwright install chromium
npm test
```

Four tests pass. In our run the whole suite took 1.2 seconds:



![Playwright HTML report for the local project showing four passed tests: signs in with the code from the simulated SMS, rejects an incorrect code, does not accept a code twice, and parses only the app's six-digit code](/_astro/playwright-report-four-local-tests.BnxjYyIO_Vac5I.webp)

The local suite in Playwright's HTML report. All four tests use the simulated sender.



### Fast tests with a simulated sender

The local suite runs a small sign-in app of its own, with its SMS provider swapped for an in-memory sender, much like an emulator. The test reads the "sent" message from the app's simulated outbox and signs in with its code:



```typescript
async function lastSimulatedCode(request: APIRequestContext): Promise<string> {
  const outbox: { body: string }[] = await (await request.get("/__simulated/sms")).json();
  return extractCode(outbox.at(-1)!.body);
}

test("signs in with the code from the simulated SMS", async ({ page, request }) => {
  await submitPassword(page);
  await submitCode(page, await lastSimulatedCode(request));
  await expectSignedIn(page);
});
```



The Playwright trace shows the order of events: the password step, the request to the simulated outbox, then the code typed into the form.



![Playwright trace viewer for the simulated SMS test, with the Fill action for a six-digit code selected after a GET request to the simulated SMS outbox, and the app's Enter your code page in the snapshot](/_astro/trace-reads-simulated-sms-code.D5U51S8L_13UFm9.webp)

The trace of the simulated sign-in. The selected step fills in the code that the test read from the simulated outbox.



These tests prove your sign-in logic and code handling. They don't prove that a text ever reaches a phone, which is why the real-number test exists.

### Test the codes that should fail

A sign-in that accepts the right code is half a feature. These two tests check that a wrong code is refused, and that a code which has already been used can't sign in again from another client:



```typescript
test("rejects an incorrect code", async ({ page, request }) => {
  await submitPassword(page);
  const code = await lastSimulatedCode(request);
  const wrong = String((Number(code) + 1) % 1_000_000).padStart(6, "0");
  await submitCode(page, wrong);
  await expect(page.getByRole("alert")).toHaveText("That code is incorrect.");
  await page.goto("/account");
  await expect(page).toHaveURL(/\/$/);
});

test("does not accept a code twice", async ({ page, request, context }) => {
  await submitPassword(page);
  const pending = (await context.cookies()).find((c) => c.name === "pending");
  const code = await lastSimulatedCode(request);
  await submitCode(page, code);
  await expectSignedIn(page);

  // Replay the same pending sign-in and code from another client.
  const replay = await request.post("/verify", {
    form: { code },
    headers: { cookie: `pending=${pending?.value}` },
    maxRedirects: 0,
  });
  expect(replay.status()).toBe(303);
  expect(replay.headers().location).toBe("/");
});
```





![Playwright trace viewer for the rejects an incorrect code test, showing the Enter your code page with the message That code is incorrect, and the expectation on the alert role selected](/_astro/trace-rejects-wrong-code.Brz3V0C-_24QnM7.webp)

The wrong-code test after Verify: the app shows That code is incorrect, and the test checks that alert.



The local app's codes also expire after five minutes and allow five attempts. If your app has rules like those, give each one a test in this fast suite, where waiting and retrying cost nothing.

### Run the real-number test

The real-number test needs a MailSlurp API key and a US phone number in the same account. Copy `.env.example` to `.env`, set `MAILSLURP_API_KEY` (and `MAILSLURP_PHONE_ID` to pick a specific number), load it into your shell and run the `sms` project:

```bash
set -a; . ./.env; set +a
npm run test:sms
```

Each run sends one real SMS to your number, so keep it off every commit. Run it by hand against the playground to see the whole flow work. For release and scheduled checks, point the same steps at your own sign-up page, so the test reads the text your own SMS provider sends your customers.



### Read real SMS codes in your tests

Create a free MailSlurp account, add a test phone number, and let Playwright, Cypress or Selenium wait for the code your app really sends.

[Start testing for free](https://app.mailslurp.com/sign-up/?onboardingRequest=phone)



## Use the same pattern in Cypress, Selenium and other runners

Nothing in the real-number test is specific to Playwright. Every version has the same four steps: record the time, request the code in the browser, wait for the text on the test number, and submit the code from it. MailSlurp has clients for JavaScript, TypeScript, Java, C#, Python and other languages, and a REST API for anything else.

### Cypress

The `cypress-mailslurp` plugin exposes the client as `cy.mailslurp()`, so the wait sits in the normal Cypress command chain. The [Cypress SMS guide](/guides/test-sms-cypress-js/) walks through Cypress SMS testing, and the [Cypress SMS example](https://github.com/mailslurp/examples/tree/master/javascript-cypress-sms-testing) signs up to the same SMS playground with a real code.

### Selenium

In a Java Selenium test, the wait uses the same conditions as the Playwright example: the number, the start time, a timeout and a body match. The test then fetches the full message to read the code from it:



```java
List<SmsPreview> previews = new WaitForControllerApi(client).waitForSms(
        new WaitForSmsConditions().phoneNumberId(phoneNumberId).since(since)
                .timeout(60_000L).unreadOnly(true).count(1L)
                .addMatchesItem(new SmsMatchOption()
                        .field(SmsMatchOption.FieldEnum.BODY)
                        .should(SmsMatchOption.ShouldEnum.CONTAIN)
                        .value("Your verification code"))).execute();
assertFalse(previews.isEmpty());
SmsDto sms = new SmsControllerApi(client).getSmsMessage(previews.get(0).getId()).execute();
```



The [Selenium Auth0 MFA example](/examples/selenium-auth0-mfa-login-test-totp-api/) shows a complete multi-factor sign-up in Java, and the [Page Object Model guide](/guides/page-object-model-e2e-mfa-testing/) keeps the message handling out of your page objects.

## OTP, MFA and 2FA testing tools

There's no single OTP testing tool, because a code can arrive three ways and each needs a different source. A complete setup pairs a browser or mobile test runner with one source per channel:

| Code arrives by | What the test needs | With MailSlurp |
| --- | --- | --- |
| SMS | A real number it can read | Phone numbers and phone pools |
| Email | An inbox it can read | Test inboxes |
| Authenticator app | The TOTP secret | [Virtual TOTP devices](/docs/totp/) |

MailSlurp's wait-for methods, such as `waitForSms` and `waitForLatestEmail`, return the next message as soon as it arrives.

For the runner, use what your team already has: Playwright, Cypress or Selenium for web apps, Appium for mobile. Provider sandboxes such as Twilio's test credentials and Firebase's test numbers are useful alongside these for fast checks of your own code.

Authenticator codes never travel by SMS or email. The test enrols a TOTP device with the secret from the app's QR code and asks it for the current code, so there's nothing to wait for. Email codes follow the same pattern as SMS with an inbox instead of a number; the [Playwright email testing guide](/blog/playwright-email-testing/) has the code. The [OTP and MFA testing docs](/docs/otp-mfa-testing/) cover all three methods, plus magic links and password resets.

## Run SMS OTP tests in CI without flaky shared numbers

Email tests can create a fresh inbox for every run. Phone numbers are rented, so tests usually share a few of them, and sharing is where SMS suites become flaky.

### Keep real texts out of retries

The example's Playwright config defines one project per run type. A plain `npx playwright test` stays local and offline, and the real run uses one worker with no retries, because a retry would send another SMS:



```typescript
export default defineConfig({
  testDir: "./tests",
  fullyParallel: false,
  workers: 1,
  retries: 0, // a retry would send another SMS
  reporter: [["list"]],
  use: { trace: "off", video: "off", screenshot: "off" },
  // Only the project being run is defined, so a plain `npx playwright test` stays local and offline.
  projects: realRun
    ? [{ name: "sms", testMatch: /playground-sms\.spec\.ts/, timeout: 120_000, use: { baseURL: "https://playground-sms.mailslurp.com" } }]
    : [{ name: "local", testMatch: /local\.spec\.ts/, use: { baseURL: `http://127.0.0.1:${port}` } }],
  // The local suite starts the demo app with a simulated SMS sender; the real run uses the playground.
  webServer: realRun
    ? undefined
    : { command: "node app/server.mjs", url: `http://127.0.0.1:${port}/`, reuseExistingServer: false, env: { SMS_PROVIDER: "memory" } },
});
```



Run `npm test` on every pull request; the example repository does this in [a GitHub Actions workflow](https://github.com/mailslurp/examples/blob/master/.github/workflows/playwright-sms-2fa-real-number.yml) that needs no secrets. Once the real-number test signs up to your own app, run it nightly or before a release, with the MailSlurp API key stored as a CI secret. The playground is a shared demo, so run the example against it by hand rather than on a schedule. If a real-number test fails, rerun it deliberately with a new `since` time rather than letting the runner retry it in a loop.

### Lease a number per job from a phone pool

When several CI jobs run at once, give each one its own number. Add your test numbers to a [phone pool](/docs/phone-pools/), and have each job lease a number at the start and release it at the end. The number stays in your account for the next job; the lease only reserves it. This example uses the REST API directly:



```javascript
const API_BASE_URL = 'https://api.mailslurp.com';

function createApi(apiKey) {
  if (!apiKey) throw new Error('Set MAILSLURP_API_KEY');

  return async function api(path, { method = 'GET', body } = {}) {
    const response = await fetch(`${API_BASE_URL}${path}`, {
      method,
      headers: {
        'x-api-key': apiKey,
        ...(body ? { 'content-type': 'application/json' } : {}),
      },
      body: body ? JSON.stringify(body) : undefined,
    });

    if (!response.ok) {
      const detail = await response.text();
      throw new Error(`MailSlurp ${method} ${path} failed (${response.status}): ${detail}`);
    }

    return response.status === 204 ? null : response.json();
  };
}
```





```javascript
async function withPhoneLease(api, poolId, workerId, exercisePhone) {
  const lease = await api(`/phone/pools/${encodeURIComponent(poolId)}/leases`, {
    method: 'POST',
    body: {
      leaseName: `SMS test for ${workerId}`,
      leaseOwner: workerId,
      leaseDurationMillis: 10 * 60 * 1000,
      acquireTimeoutMillis: 30 * 1000,
    },
  });
  const since = new Date();

  try {
    return await exercisePhone(lease, since);
  } finally {
    await api(
      `/phone/pools/${encodeURIComponent(poolId)}/leases/${encodeURIComponent(lease.id)}`,
      { method: 'DELETE' },
    );
  }
}
```



Inside `exercisePhone`, use `lease.phoneNumber` in your app and call `waitForSms` with `lease.phoneNumberId` and the supplied `since`. Make the lease duration longer than the whole test, including the SMS wait. If acquisition times out, every number is busy: treat that as a setup failure and add numbers or reduce parallelism, rather than falling back to a number another job might be using.

### Keep codes out of build logs

A live code in a public build log is a live code. Log the message ID and the delivery time, not the message body. The [email and SMS CI guide](/guides/email-sms-ci-diagnostics/) has a GitHub Actions workflow with a concurrency group for a shared number, and shows how to keep codes out of the output.

## Choose a test number your SMS provider will deliver to

The number decides what you're really testing. A fictional number such as `+1 202 555 0143` is fine for simulated tests and receives nothing. A shared number from a public website tests whether a stranger got there first. A private number in your users' country tests the route your customers actually use.

MailSlurp numbers are available in these countries:

| Country | Number types |
| --- | --- |
| United States | Local, toll-free, optional non-VoIP filter |
| United Kingdom | Mobile, optional non-VoIP filter |
| Australia | Mobile, optional non-VoIP filter |
| Canada | Local |
| Netherlands, Sweden, Finland, Estonia, Poland, Israel | Mobile |

A few things to check when choosing a test phone number for OTP:

- **Non-VoIP.** Some senders and verification services refuse numbers they classify as VoIP. In the US, UK and Australia you can filter for non-VoIP numbers. The filter improves the odds, but no number type guarantees that every third-party sender will accept it.
- **Short codes and sender IDs.** If your app sends from a short code or an alphanumeric sender ID, check that the number type you choose can receive from it in that country.
- **US registration.** In the US, application texts from a long code need A2P 10DLC registration with your provider; unregistered traffic is often filtered before it reaches any number.
- **Toll-free.** US toll-free numbers are available for testing toll-free sending; the [toll-free SMS guide](/blog/text-enabled-toll-free-numbers-for-sms/) explains what's different about that route.
- **How many.** One number per parallel job that tests SMS, plus any you keep for manual checks.

Numbers are rented monthly or yearly. [Pricing](https://app.mailslurp.com/pricing/) lists the current rental and message costs, and the [SMS testing overview](/testing/sms-testing/) and [phone number docs](/docs/txt-sms/) cover provisioning through the dashboard and the API.

## Frequently asked questions

### Do Twilio test credentials send a real SMS?

No. With test credentials, Twilio validates the request and returns a message, but it doesn't connect to real phone numbers or charge your account, and status callbacks don't fire. They're useful for checking that your code calls Twilio correctly. To test delivery, send with live credentials to a number your test can read.

### Is Twilio's Virtual Phone the same as testing with a real number?

No. The Virtual Phone shows messages sent from your Twilio numbers in the Twilio Console, and Twilio describes it as testing without going over a carrier network or using a real recipient device. It's handy while building an SMS feature, but it can't show whether a real carrier delivers your text, or whether a test can read the code without a person.

### Can I use a free receive-SMS website for OTP testing?

It's a poor fit for automated tests. The numbers are shared with everyone who visits the site, any code sent to them can be read by anyone, and many services block them. A private test number gives your test the only copy of the code and a stable number to register with.

### Why does my app's SMS provider reject the test phone number?

The most common reasons are a number type the sender doesn't support, such as a VoIP or toll-free number, and a destination country the account isn't allowed to send to. Choose a mobile or non-VoIP number in a country your provider delivers to, and check the provider's error code for the exact reason.

### How long should a test wait for an OTP SMS?

Long enough for a slow but acceptable delivery, and shorter than the code's expiry. Sixty seconds works for most routes. Measure real delivery times with the report annotation in the example, and treat a text that arrives after the code has expired as a failure even if the test would have waited for it.

### Can two tests share one phone number?

Only if they never request codes at the same time. Two tests waiting on the same number can each read the other's code. Run tests that share a number one at a time, give each parallel job its own number, or lease numbers from a phone pool.

### Do I need to change SMS provider to use MailSlurp numbers?

No. Your app keeps sending through its own provider, such as Twilio, Vonage or Sinch, to whatever number the test account has. MailSlurp receives the text on that number and makes it available to your test. Testing through your real provider is the point: it's the route your customers use.

### Can I test SMS OTP without sending real messages?

Yes, and you should for most tests. A simulated sender, like the in-memory one in the example, checks the right code, wrong codes, replays and expiry in about a second without network access. Keep one real-number test for releases, because only a real text shows that the provider, the route and the template work together.
