> ## Documentation Index
> Fetch the complete documentation index at: https://launchdarkly.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Test data sources

<View title="Developer" />

<View title="Federal docs" />

<View title="EU docs" />

This topic explains how to use the test data source feature for more control over your LaunchDarkly SDKs during testing.

<Note>
  **Newer versions of LaunchDarkly SDKs replace users with contexts**

  A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. Contexts replace another data object in LaunchDarkly: "users." To learn more, read [Contexts](/docs/home/flags/contexts).

  Creating contexts and evaluating flags based on them is supported in the latest major versions of [most of our SDKs](/docs/sdk). For these SDKs, the code samples on this page include the two most recent versions.
</Note>

## About test data sources

LaunchDarkly SDKs must have a data source when they initialize. Usually, this data source is connected to LaunchDarkly. However, when you write unit tests, using a test data source can give you more control over your SDK.

LaunchDarkly supports a test data source for some SDKs. The test data source allows you to mock the behavior of a LaunchDarkly SDK so it has predictable behavior when evaluating flags.

<Warning>
  **Use the test data source for testing only**

  The test data source is intended strictly for testing purposes. It cannot be used in production.
</Warning>

You can set a flag's initial state by calling the data source's `update` method before or after starting the client. When you start the client, it acts as if it has connected to LaunchDarkly and received all of the test data that you have configured. Subsequent calls to `update` behave as if LaunchDarkly sent an update over a streaming connection.

You can modify targeting rules at any time, including when the SDK is already in use. This allows you to simulate a situation where a feature flag changes values. When you set a flag's state in the test data source, you can either set it to return a single variation for all contexts or users, or set up more complicated behavior similar to the ways you can configure a flag in the **Flags** list. This can be useful in testing application code that expects flags to be different for different contexts or users.

Details about each SDK's configuration are available in the SDK-specific sections below.

## Client-side SDKs

This feature is available in the following client-side SDKs:

* [.NET (client-side)](#net-client-side)
* [Android](#android)

### .NET (client-side)

<Accordion title="Expand .NET (client-side) code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```csharp title=".NET SDK v5.0+ (C#)" lines wrap theme={null}
    using LaunchDarkly.Sdk.Client.Integrations;

    var td = TestData.DataSource();
    // You can set any initial flag states here with td.Update

    var config = Configuration
        .Builder("example-mobile-key", ConfigurationBuilder.AutoEnvAttributes.Enabled)
        .DataSource(td)
        .Build();
    var client = LdClient.Init(config, context, startWaitTime);
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```csharp title="C#" lines wrap theme={null}
    td.Update(td.Flag("example-flag-key").Variation(false));
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```csharp title=".NET SDK v5.0+ (C#)" lines wrap theme={null}
    // This flag is true for the context key "example-context-key" and false for everyone else
    td.Update(td.Flag("flag-key-456def")
        .Variation(false)
        .VariationForKey(ContextKind.Of("user"), "example-context-key", true));

    // This flag returns the string variation "green" for contexts where the custom
    // attribute "admin" has a value of true, and "red" for all other contexts.
    td.Update(td.Flag("flag-key-789ghi")
        .Variations(LdValue.Of("red"), LdValue.Of("green"))
        .VariationFunc(context =>
            context.GetValue("admin").AsBool ? 1 : 0));
    ```
  </CodeGroup>

  To learn more, read [TestData](https://launchdarkly.github.io/dotnet-core/pkgs/sdk/client/api/LaunchDarkly.Sdk.Client.Integrations.TestData.html).
</Accordion>

### Android

<Accordion title="Expand Android code sample">
  This feature is available in versions 4.0 and higher of the Android SDK.

  To configure the SDK to use a test data source:

  <CodeGroup>
    ```java title="Java" lines wrap theme={null}
    import com.launchdarkly.sdk.*;
    import com.launchdarkly.sdk.android.*;
    import com.launchdarkly.sdk.android.integrations.*;

    TestData td = TestData.dataSource();
    // You can set any initial flag states here with td.update

    LDConfig config = new LDConfig.Builder(AutoEnvAttributes.Enabled)
      .mobileKey("example-mobile-key")
      .dataSource(td)
      .build();
    LDClient client = LDClient.init(this.getApplication(), config, context, secondsToBlock);
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```java title="Java" lines wrap theme={null}
    td.update(td.flag("example-flag-key").variation(false));
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```java title="Java" lines wrap theme={null}
    // This flag is true for the context with the key "example-context-key" and kind of "organization",
    // and false for everyone else
    td.update(td.flag("example-flag-key")
      .variation(false)
      .variationForKey(ContextKind.of("organization"), "example-context-key", true));

    // This flag returns the string variation "green" for contexts who have the custom
    // attribute "admin" with a value of true, and "red" for everyone else.
    td.update(td.flag("example-string-flag-key")
      .variations(LDValue.of("red"), LDValue.of("green"))
      .variationIndexFunc(context ->
        context.getValue("admin").booleanValue() ? 1 : 0));
    ```
  </CodeGroup>

  To learn more, read [`TestData`](https://launchdarkly.github.io/android-client-sdk/com/launchdarkly/sdk/android/integrations/TestData.html).
</Accordion>

## Server-side SDKs

This feature is available in the following server-side SDKs:

* [.NET (server-side)](#net-server-side)
* [Erlang](#erlang)
* [Go](#go)
* [Haskell](#haskell)
* [Java](#java)
* [Node.js (server-side)](#node-js-server-side)
* [PHP](#php)
* [Python](#python)
* [Ruby](#ruby)
* [Rust](#rust)

### .NET (server-side)

<Accordion title="Expand .NET (server-side) code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```csharp title="C#" lines wrap theme={null}
    using LaunchDarkly.Sdk.Server.Integrations;

    var td = TestData.DataSource();
    // You can set any initial flag states here with td.Update

    var config = Configuration.Builder("YOUR_SDK_KEY")
        .DataSource(td)
        .Build();
    var client = new LdClient(config);
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```csharp title=".NET SDK v7.0+ (C#)" lines wrap theme={null}
    td.Update(td.Flag("example-flag-key").VariationForAll(false));
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```csharp title=".NET SDK v7.0+ (C#)" lines wrap theme={null}
    // This flag is true for the context with the key "example-context-key" and kind of "organization",
    // and false for everyone else
    td.Update(td.Flag("flag-key-456def")
        .VariationForKey(ContextKind.Of("organization"), "example-context-key", true)
        .FallthroughVariation(false));

    // This flag returns the string variation "green" for contexts that have the
    // attribute "admin" with a value of true, and "red" for everyone else.
    td.Update(td.Flag("flag-key-789ghi")
        .Variations(LdValue.Of("red"), LdValue.Of("green"))
        .FallthroughVariation(0)
        .IfMatch("admin", LdValue.Of(true))
        .ThenReturn(1));
    ```
  </CodeGroup>

  To learn more, read [`TestData`](https://launchdarkly.github.io/dotnet-core/pkgs/sdk/server/api/LaunchDarkly.Sdk.Server.Integrations.TestData.html).
</Accordion>

### Erlang

<Accordion title="Expand Erlang code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```erlang title="Erlang" lines wrap theme={null}
    Options = #{
      datasource => testdata,
      send_events => false,
      feature_store => ldclient_storage_map
    },
    ldclient:start_instance(SdkKey, Options),
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```erlang title="Erlang SDK v2.0+" lines wrap theme={null}
    {ok, Flag} = ldclient_testdata:flag("example-flag-key"),
    ldclient_testdata:update(ldclient_flagbuilder:variation_for_all(true, Flag)),
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```erlang title="Erlang SDK v2.0+" lines wrap theme={null}
    %% This flag is true for the context key "example-user-key" and false for everyone else
    {ok, Flag2} = ldclient_testdata:flag("flag-key-456def"),
    UpdatedFlag2 = ldclient_flagbuilder:fallthrough_variation(false,
      ldclient_flagbuilder:variation_for_context(true,  <<"user">>, <<"example-user-key">>, Flag2)
    ),
    ldclient_testdata:update(UpdatedFlag2),

    %% This flag returns the string variation "green" for contexts that have the custom
    %% attribute "admin" with a value of true, and "red" for everyone else.
    {ok, Flag} = ldclient_testdata:flag("flag-key-789ghi"),
    UpdatedFlag = ldclient_flagbuilder:fallthrough_variation(0,
                  ldclient_flagbuilder:then_return(1,
                  ldclient_flagbuilder:if_match(<<"user">>, <<"admin">>, [true],
                  ldclient_flagbuilder:variations([<<"red">>, <<"green">>], Flag)))),
    ldclient_testdata:update(UpdatedFlag),
    ```
  </CodeGroup>
</Accordion>

### Go

<Accordion title="Expand Go code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```go title="Go SDK v6+" lines wrap theme={null}
    import (
        ld "github.com/launchdarkly/go-server-sdk/v6"
        "github.com/launchdarkly/go-server-sdk/v6/testhelpers/ldtestdata"
        "github.com/launchdarkly/go-sdk-common/v3/ldcontext"
        "github.com/launchdarkly/go-sdk-common/v3/ldvalue"
    )

    td := ldtestdata.DataSource()
    // You can set any initial flag states here with td.Update

    config := ld.Config{
        DataSource: td,
    }
    client, _ := ld.MakeCustomClient("YOUR_SDK_KEY", config, 0)
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```go title="Go SDK v6+" lines wrap theme={null}
    td.Update(td.Flag("example-flag-key").VariationForAll(false))
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```go title="Go SDK v6+" expandable lines wrap theme={null}
    import (
        "github.com/launchdarkly/go-sdk-common/v3/ldvalue"
    )

    // This flag is true for the context with the key "example-context-key" and kind of "organization",
    // and false for everyone else
    td.Update(td.Flag("flag-key-456def").
        VariationForKey("organization", "example-context-key", true).
        FallthroughVariation(false));


    // This flag returns the string variation "green" for contexts that have the
    // attribute "admin" with a value of true, and "red" for everyone else.
    td.Update(td.Flag("flag-key-789ghi").
        Variations(ldvalue.String("red"), ldvalue.String("green")).
        FallthroughVariationIndex(0).
        IfMatch("admin", ldvalue.Bool(true)).
        ThenReturnIndex(1));
    ```
  </CodeGroup>

  To learn more, read [`ldtestdata`](https://pkg.go.dev/github.com/launchdarkly/go-server-sdk/v7/testhelpers/ldtestdata).
</Accordion>

### Haskell

<Accordion title="Expand Haskell code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```haskell title="Haskell" lines wrap theme={null}
    import qualified LaunchDarkly.Server as LD
    import qualified LaunchDarkly.Server.Integrations.TestData as TestData

    td <- TestData.newTestData
    let config = LD.configSetDataSourceFactory (Just $ TestData.dataSourceFactory td) $ LD.makeConfig "YOUR_SDK_KEY"
    client <- LD.makeClient config
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```haskell title="Haskell SDK v4.0" lines wrap theme={null}
    TestData.update td =<< ( TestData.flag td "example-flag-key"
    	<&> TestData.booleanFlag
    	<&> TestData.variationForAll True
    )
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```haskell title="Haskell SDK v4.0" lines wrap theme={null}
    -- This flag is true for the context with kind "context-kind" and key "example-context-key", and false for everyone else
    TestData.update td =<< ( TestData.flag td "flag-key-456def"
    	<&> TestData.booleanFlag
    	<&> TestData.variationForKey "context-kind" "example-context-key" (0 :: TestData.VariationIndex)
    	<&> TestData.fallthroughVariation (1 :: TestData.VariationIndex)
    )

    -- This flag returns the string variation "green" for contexts with kind "context-kind"
    -- that have the custom attribute "admin" with a value of true, and "red" for everyone else.
    TestData.update td =<< ( TestData.flag td "flag-key-789ghi"
    	<&> TestData.variations [toJSON "red", toJSON "green"]
    	<&> TestData.ifMatchContext "context-kind" "admin" [Aeson.Bool True]
    	<&> TestData.thenReturn (1 :: TestData.VariationIndex)
    	<&> TestData.fallthroughVariation (0 :: TestData.VariationIndex)
    )
    ```
  </CodeGroup>
</Accordion>

### Java

<Accordion title="Expand Java code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```java title="Java" lines wrap theme={null}
    import com.launchdarkly.sdk.*;
    import com.launchdarkly.sdk.server.*;
    import com.launchdarkly.sdk.server.integrations.*;

    TestData td = TestData.dataSource();
    // You can set any initial flag states here with td.update

    LDConfig config = new LDConfig.Builder()
        .dataSource(td)
        .build();
    LDClient client = new LDClient(sdkKey, config);
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```java title="Java SDK v6.0+" lines wrap theme={null}
    td.update(td.flag("example-flag-key").variationForAll(false));
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```java title="Java SDK v6.0+" lines wrap theme={null}
    // This flag is true for the context with the key "example-context-key" and kind of "organization",
    // and false for everyone else
    td.update(td.flag("example-flag-key")
      .variationForKey(ContextKind.of("organization"), "example-context-key", true)
      .fallthroughVariation(false));

    // This flag returns the string variation "green" for contexts who have the custom
    // attribute "admin" with a value of true, and "red" for everyone else.
    td.update(td.flag("example-string-flag-key")
      .variations(LDValue.of("red"), LDValue.of("green"))
      .fallthroughVariation(0)
      .ifMatch("admin", LDValue.of(true))
      .thenReturn(1));
    ```
  </CodeGroup>

  To learn more, read [`TestData`](https://launchdarkly.github.io/java-core/lib/sdk/server/com/launchdarkly/sdk/server/integrations/TestData.html).
</Accordion>

### Node.js (server-side)

<Accordion title="Expand Node.js (server-side) code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```js title="Node.js SDK v8.x+ (JavaScript)" lines wrap theme={null}
    const ld = require('@launchdarkly/node-server-sdk');
    const { TestData } = require('@launchdarkly/node-server-sdk/integrations');

    const td = new TestData();
    td.update(td.flag('example-flag-key').booleanFlag().variationForAll(true));
    const client = ld.init('YOUR_SDK_KEY', { updateProcessor: td.getFactory() });

    // flags can be updated at any time:
    td.update(td.flag('flag-key-456def')
        .variationForUser('example-user-key', true)
        .fallthroughVariation(false));

    ```
  </CodeGroup>

  To learn more, read [`TestData`](https://launchdarkly.github.io/js-core/packages/sdk/server-node/docs/classes/TestData.html).
</Accordion>

### PHP

<Accordion title="Expand PHP code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```php title="PHP" lines wrap theme={null}
    require 'vendor/autoload.php';

    $td = new LaunchDarkly\Integrations\TestData();
    // You can set any initial flag states here with td.update

    $client = new LaunchDarkly\LDClient("YOUR_SDK_KEY", ['feature_requester' => $td]);
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```php title="PHP SDK v5.0+" lines wrap theme={null}
    $td->update($td->flag("example-flag-key")->variationForAll(false));
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```php title="PHP SDK v5.0+" expandable lines wrap theme={null}
    // This flag is true for the context with the key "example-context-key" and kind of "organization",
    // and false for everyone else
    $td->update(
        $td->flag("example-flag-key")
           ->variationForKey("organization", "example-context-key", true)
           ->fallthroughVariation(false)
    );

    // This flag returns the string variation "green" for contexts that have the custom
    // attribute "admin" with a value of true, and "red" for everyone else.
    $td->update(
        $td->flag("example-string-flag-key")
           ->variations("red", "green")
           ->fallthroughVariation(0)
           ->ifMatch("admin", true)
           ->thenReturn(1)
    );
    ```
  </CodeGroup>

  To learn more, read [`TestData`](https://launchdarkly.github.io/php-server-sdk/classes/LaunchDarkly-Integrations-TestData.html).
</Accordion>

### Python

<Accordion title="Expand Python code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```python title="Python" lines wrap theme={null}
    from ldclient.integrations.test_data import TestData
    from ldclient import LDClient, Config

    td = TestData.data_source()
    # You can set any initial flag states here with td.update
    client = LDClient(config=Config("YOUR_SDK_KEY", update_processor_class = td))
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```python title="Python SDK v8.0+" lines wrap theme={null}
    td.update(td.flag("example-flag-key").variation_for_all(True))
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```python title="Python SDK v8.0+" maxLines=0 expandable lines wrap theme={null}
    # This flag is true for the context with the key "example-context-key" and kind
    # of "organization", and false for everyone else.

    td.update(
        td.flag("flag-key-456def") \
            .variation_for_key("organization", "example-context-key", True) \
            .fallthrough_variation(False)
    )

    # This flag returns the string variation "green" for contexts of the kind "user"
    # who have the custom attribute "admin" with a value of true, and "red" for
    # everyone else.
    td.update(
        td.flag("flag-key-789ghi") \
            .variations("red", "green")
            .fallthrough_variation(0)
            .if_match_context("user", "admin", True)
            .then_return(1)
    )
    ```
  </CodeGroup>

  To learn more, read [`TestData`](https://launchdarkly-python-sdk.readthedocs.io/en/latest/api-testing.html#ldclient-integrations-test-data-module).
</Accordion>

### Ruby

<Accordion title="Expand Ruby code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```ruby title="Ruby" lines wrap theme={null}
    require 'ldclient-rb'

    td = LaunchDarkly::Integrations::TestData.data_source
    # You can set any initial flag states here with td.update

    config = LaunchDarkly::Config.new(data_source: td)
    client = LaunchDarkly::LDClient.new("YOUR_SDK_KEY", config)
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```ruby title="Ruby SDK v7.0+" lines wrap theme={null}
    td.update(td.flag("example-flag-key").variation_for_all(false))
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```ruby title="Ruby SDK v7.0+" lines wrap theme={null}
    # This flag is true for the context key "example-context-key" and false for everyone else
    td.update(td.flag("flag-key-456def").
        variation_for_user("example-context-key", true).
        fallthrough_variation(false))

    # This flag returns the string variation "green" for contexts who have the custom
    # attribute "admin" with a value of true, and "red" for everyone else.
    td.update(td.flag("flag-key-789ghi").
        variations("red", "green").
        fallthrough_variation(0).
        if_match_context("user", "admin", true).then_return(1))
    ```
  </CodeGroup>

  To learn more, read [`TestData`](https://launchdarkly.github.io/ruby-server-sdk/LaunchDarkly/Integrations/TestData.html).
</Accordion>

### Rust

<Accordion title="Expand Rust code sample">
  To configure the SDK to use a test data source:

  <CodeGroup>
    ```rust title="Rust" lines wrap theme={null}
    use launchdarkly_server_sdk::{Client, ConfigBuilder, TestData, FlagBuilder};

    let td = TestData::new();
    // You can set any initial flag states here with td.update

    let config = ConfigBuilder::new("YOUR_SDK_KEY")
        .data_source(&td)
        .build()
        .unwrap();
    let client = Client::build(config).unwrap();
    client.start_with_default_executor();
    ```
  </CodeGroup>

  To set a flag to a specific value:

  <CodeGroup>
    ```rust title="Rust SDK v3.0" lines wrap theme={null}
    td.update(FlagBuilder::new("example-flag-key").variation_for_all(false));
    ```
  </CodeGroup>

  There are other ways you can configure flag behavior using a test data source. Here is an example:

  <CodeGroup>
    ```rust title="Rust SDK v3.0" expandable lines wrap theme={null}
    use launchdarkly_server_sdk::{AttributeValue, FlagValue, Kind};
    use std::convert::TryFrom;

    // This flag is true for the context with the key "example-context-key" and kind of "organization",
    // and false for everyone else
    td.update(FlagBuilder::new("flag-key-456def")
        .variation_for_key(Kind::try_from("organization").unwrap(), "example-context-key", true)
        .fallthrough_variation(false));

    // This flag returns the string variation "green" for contexts that have the
    // attribute "admin" with a value of true, and "red" for everyone else.
    td.update(FlagBuilder::new("flag-key-789ghi")
        .variations(vec![FlagValue::Str("red".into()), FlagValue::Str("green".into())])
        .fallthrough_variation_index(0)
        .if_match("admin", vec![AttributeValue::Bool(true)])
        .then_return_index(1));
    ```
  </CodeGroup>

  To learn more, read [`TestData`](https://docs.rs/launchdarkly-server-sdk/latest/launchdarkly_server_sdk/struct.TestData.html).
</Accordion>
