{"id":13604366,"url":"https://github.com/google/TestParameterInjector","last_synced_at":"2025-04-11T23:32:25.773Z","repository":{"id":41116495,"uuid":"339537434","full_name":"google/TestParameterInjector","owner":"google","description":"A simple yet powerful parameterized test runner for Java.","archived":false,"fork":false,"pushed_at":"2024-11-05T13:47:51.000Z","size":2433,"stargazers_count":397,"open_issues_count":6,"forks_count":34,"subscribers_count":6,"default_branch":"main","last_synced_at":"2024-11-07T08:42:53.941Z","etag":null,"topics":["java","junit4","junit5","parameterized-tests","testing"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/google.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-02-16T21:34:24.000Z","updated_at":"2024-11-05T13:47:16.000Z","dependencies_parsed_at":"2023-12-05T11:30:36.517Z","dependency_job_id":"ac511044-43e2-4e56-852f-f194de1329c6","html_url":"https://github.com/google/TestParameterInjector","commit_stats":null,"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2FTestParameterInjector","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2FTestParameterInjector/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2FTestParameterInjector/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2FTestParameterInjector/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/google","download_url":"https://codeload.github.com/google/TestParameterInjector/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248495250,"owners_count":21113592,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java","junit4","junit5","parameterized-tests","testing"],"created_at":"2024-08-01T19:00:44.298Z","updated_at":"2025-04-11T23:32:20.762Z","avatar_url":"https://github.com/google.png","language":"Java","readme":"TestParameterInjector\n=====================\n\n[Link to Javadoc.](https://google.github.io/TestParameterInjector/docs/latest/)\n\n## Introduction\n\n`TestParameterInjector` is a JUnit4 and JUnit5 test runner that runs its test methods for\ndifferent combinations of field/parameter values.\n\nParameterized tests are a great way to avoid code duplication between tests and\npromote high test coverage for data-driven tests.\n\nThere are a lot of alternative parameterized test frameworks, such as\n[junit.runners.Parameterized](https://github.com/junit-team/junit4/wiki/parameterized-tests)\nand [JUnitParams](https://github.com/Pragmatists/JUnitParams). We believe\n`TestParameterInjector` is an improvement of those because it is more powerful\nand simpler to use.\n\n[This blogpost](https://opensource.googleblog.com/2021/03/introducing-testparameterinjector.html)\ngoes into a bit more detail about how `TestParameterInjector` compares to other\nframeworks used at Google.\n\n## Getting started\n\n### JUnit4\n\nTo start using `TestParameterInjector` right away, copy the following snippet:\n\n```java\nimport com.google.testing.junit.testparameterinjector.TestParameterInjector;\nimport com.google.testing.junit.testparameterinjector.TestParameter;\n\n@RunWith(TestParameterInjector.class)\npublic class MyTest {\n\n  @TestParameter boolean isDryRun;\n\n  @Test public void test1(@TestParameter boolean enableFlag) {\n    // ...\n  }\n\n  @Test public void test2(@TestParameter MyEnum myEnum) {\n    // ...\n  }\n\n  enum MyEnum { VALUE_A, VALUE_B, VALUE_C }\n}\n```\n\nAnd add the following dependency to your `.pom` file:\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003ecom.google.testparameterinjector\u003c/groupId\u003e\n  \u003cartifactId\u003etest-parameter-injector\u003c/artifactId\u003e\n  \u003cversion\u003e1.18\u003c/version\u003e\n  \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nor see [this maven.org\npage](https://search.maven.org/artifact/com.google.testparameterinjector/test-parameter-injector)\nfor instructions for other build tools.\n\n### JUnit5 (Jupiter)\n\u003cdetails\u003e\n\u003csummary\u003eClick to expand\u003c/summary\u003e\n\nTo start using `TestParameterInjector` right away, copy the following snippet:\n\n```java\nimport com.google.testing.junit.testparameterinjector.junit5.TestParameterInjectorTest;\nimport com.google.testing.junit.testparameterinjector.junit5.TestParameter;\n\nclass MyTest {\n\n  @TestParameter boolean isDryRun;\n\n  @TestParameterInjectorTest\n  void test1(@TestParameter boolean enableFlag) {\n    // ...\n  }\n\n  @TestParameterInjectorTest\n  void test2(@TestParameter MyEnum myEnum) {\n    // ...\n  }\n\n  enum MyEnum { VALUE_A, VALUE_B, VALUE_C }\n}\n```\n\nAnd add the following dependency to your `.pom` file:\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003ecom.google.testparameterinjector\u003c/groupId\u003e\n  \u003cartifactId\u003etest-parameter-injector-junit5\u003c/artifactId\u003e\n  \u003cversion\u003e1.18\u003c/version\u003e\n  \u003cscope\u003etest\u003c/scope\u003e\n\u003c/dependency\u003e\n```\n\nor see [this maven.org\npage](https://search.maven.org/artifact/com.google.testparameterinjector/test-parameter-injector-junit5)\nfor instructions for other build tools.\n\n\u003c/details\u003e\n\n## Basics\n\n**Note about JUnit4 vs JUnit5:**\u003cbr /\u003e\nThe code below assumes you're using JUnit4. For JUnit5 users, simply remove the\n`@RunWith` annotation and replace `@Test` by `@TestParameterInjectorTest`.\n\n### `@TestParameter` for testing all combinations\n\n#### Parameterizing a single test method\n\nThe simplest way to use this library is to use `@TestParameter`. For example:\n\n```java\n@RunWith(TestParameterInjector.class)\npublic class MyTest {\n\n  @Test\n  public void test(@TestParameter boolean isOwner) {...}\n}\n```\n\nIn this example, two tests will be automatically generated by the test framework:\n\n-   One with `isOwner` set to `true`\n-   One with `isOwner` set to `false`\n\nWhen running the tests, the result will show the following test names:\n\n```\nMyTest#test[isOwner=true]\nMyTest#test[isOwner=false]\n```\n\n#### Parameterizing the whole class\n\n`@TestParameter` can also annotate a field:\n\n```java\n@RunWith(TestParameterInjector.class)\npublic class MyTest {\n\n  @TestParameter private boolean isOwner;\n\n  @Test public void test1() {...}\n  @Test public void test2() {...}\n}\n```\n\nIn this example, both `test1` and `test2` will be run twice (once for each\nparameter value).\n\nThe test runner will set these fields before calling any methods, so it is safe\nto use such `@TestParameter`-annotated fields for setting up other test values\nand behavior in `@Before` methods.\n\n#### Supported types\n\nThe following examples show most of the supported types. See the `@TestParameter` javadoc for more details. \n\n```java\n// Enums\n@TestParameter AnimalEnum a; // Implies all possible values of AnimalEnum\n@TestParameter({\"CAT\", \"DOG\"}) AnimalEnum a; // Implies AnimalEnum.CAT and AnimalEnum.DOG.\n\n// Strings\n@TestParameter({\"cat\", \"dog\"}) String animalName;\n\n// Java primitives\n@TestParameter boolean b; // Implies {true, false}\n@TestParameter({\"1\", \"2\", \"3\"}) int i;\n@TestParameter({\"1\", \"1.5\", \"2\"}) double d;\n\n// Bytes\n@TestParameter({\"!!binary 'ZGF0YQ=='\", \"some_string\"}) byte[] bytes;\n\n// Durations (segments of number+unit as shown below)\n@TestParameter({\"1d\", \"2h\", \"3min\", \"4s\", \"5ms\", \"6us\", \"7ns\"}) java.time.Duration d;\n@TestParameter({\"1h30min\", \"-2h10min20s\", \"1.5h\", \".5s\", \"0\"}) java.time.Duration d;\n```\n\nFor non-primitive types (e.g. String, enums, bytes), `\"null\"` is always parsed as the `null` reference.\n\n#### Multiple parameters: All combinations are run\n\nIf there are multiple `@TestParameter`-annotated values applicable to one test\nmethod, the test is run for all possible combinations of those values. Example:\n\n```java\n@RunWith(TestParameterInjector.class)\npublic class MyTest {\n\n  @TestParameter private boolean a;\n\n  @Test public void test1(@TestParameter boolean b, @TestParameter boolean c) {\n    // Run for these combinations:\n    //   (a=false, b=false, c=false)\n    //   (a=false, b=false, c=true )\n    //   (a=false, b=true,  c=false)\n    //   (a=false, b=true,  c=true )\n    //   (a=true,  b=false, c=false)\n    //   (a=true,  b=false, c=true )\n    //   (a=true,  b=true,  c=false)\n    //   (a=true,  b=true,  c=true )\n  }\n}\n```\n\nIf you want to explicitly define which combinations are run, see the next\nsections.\n\n### Use a test enum for enumerating more complex parameter combinations\n\nUse this strategy if you want to:\n\n-   Explicitly specify the combination of parameters\n-   or your parameters are too large to be encoded in a `String` in a readable\n    way\n\nExample:\n\n```java\n@RunWith(TestParameterInjector.class)\nclass MyTest {\n\n  enum FruitVolumeTestCase {\n    APPLE(Fruit.newBuilder().setName(\"Apple\").setShape(SPHERE).build(), /* expectedVolume= */ 3.1),\n    BANANA(Fruit.newBuilder().setName(\"Banana\").setShape(CURVED).build(), /* expectedVolume= */ 2.1),\n    MELON(Fruit.newBuilder().setName(\"Melon\").setShape(SPHERE).build(), /* expectedVolume= */ 6);\n\n    final Fruit fruit;\n    final double expectedVolume;\n\n    FruitVolumeTestCase(Fruit fruit, double expectedVolume) { ... }\n  }\n\n  @Test\n  public void calculateVolume_success(@TestParameter FruitVolumeTestCase fruitVolumeTestCase) {\n    assertThat(calculateVolume(fruitVolumeTestCase.fruit))\n        .isEqualTo(fruitVolumeTestCase.expectedVolume);\n  }\n}\n```\n\nThe enum constant name has the added benefit of making for sensible test names:\n\n```\nMyTest#calculateVolume_success[APPLE]\nMyTest#calculateVolume_success[BANANA]\nMyTest#calculateVolume_success[MELON]\n```\n\n### `@TestParameters` for defining sets of parameters\n\nYou can also explicitly enumerate the sets of test parameters via a list of YAML\nmappings:\n\n```java\n@Test\n@TestParameters(\"{age: 17, expectIsAdult: false}\")\n@TestParameters(\"{age: 22, expectIsAdult: true}\")\npublic void personIsAdult(int age, boolean expectIsAdult) { ... }\n```\n\nwhich would generate the following tests:\n\n```\nMyTest#personIsAdult[{age: 17, expectIsAdult: false}]\nMyTest#personIsAdult[{age: 22, expectIsAdult: true}]\n```\n\nThe string format supports the same types as `@TestParameter` (e.g. enums). See\nthe `@TestParameters` javadoc for more info.\n\n`@TestParameters` works in the same way on the constructor, in which case all\ntests will be run for the given parameter sets.\n\n\u003e Tip: Consider setting a custom name if the YAML string is large:\n\u003e\n\u003e ```java\n\u003e @Test\n\u003e @TestParameters(customName = \"teenager\", value = \"{age: 17, expectIsAdult: false}\")\n\u003e @TestParameters(customName = \"young adult\", value = \"{age: 22, expectIsAdult: true}\")\n\u003e public void personIsAdult(int age, boolean expectIsAdult) { ... }\n\u003e ```\n\u003e\n\u003e This will generate the following test names:\n\u003e\n\u003e ```\n\u003e MyTest#personIsAdult[teenager]\n\u003e MyTest#personIsAdult[young adult]\n\u003e ```\n\n### Filtering unwanted parameters\n\nSometimes, you want to exclude a parameter or a combination of parameters. We\nrecommend doing this via JUnit assumptions which is also supported by\n[Truth](https://truth.dev/):\n\n```java\nimport static com.google.common.truth.TruthJUnit.assume;\n\n@Test\npublic void myTest(@TestParameter Fruit fruit) {\n  assume().that(fruit).isNotEqualTo(Fruit.BANANA);\n\n  // At this point, the test will only run for APPLE and CHERRY.\n  // The BANANA case will silently be ignored.\n}\n\nenum Fruit { APPLE, BANANA, CHERRY }\n```\n\nNote that the above works regardless of what parameterization framework you\nchoose.\n\n## Advanced usage\n\n**Note about JUnit4 vs JUnit5:**\u003cbr /\u003e\nThe code below assumes you're using JUnit4. For JUnit5 users, simply remove the\n`@RunWith` annotation and replace `@Test` by `@TestParameterInjectorTest`.\n\n### Dynamic parameter generation for `@TestParameter`\n\nInstead of providing a list of parsable strings, you can implement your own\n`TestParameterValuesProvider` as follows:\n\n```java\nimport com.google.testing.junit.testparameterinjector.TestParameterValuesProvider;\n\n@Test\npublic void matchesAllOf_throwsOnNull(\n    @TestParameter(valuesProvider = CharMatcherProvider.class) CharMatcher charMatcher) {\n  assertThrows(NullPointerException.class, () -\u003e charMatcher.matchesAllOf(null));\n}\n\nprivate static final class CharMatcherProvider extends TestParameterValuesProvider {\n  @Override\n  public List\u003cCharMatcher\u003e provideValues(Context context) {\n    return ImmutableList.of(CharMatcher.any(), CharMatcher.ascii(), CharMatcher.whitespace());\n  }\n}\n```\n\nNotes:\n\n-   The `provideValues()` method can dynamically construct the returned list,\n    e.g. by reading a file.\n-   There are no restrictions on the object types returned.\n-   The `provideValues()` method is called before `@BeforeClass`, so don't rely\n    on any static state initialized in there.\n-   The returned objects' `toString()` will be used for the test names. If you\n    want to customize the value names, you can do that as follows:\n\n    ```\n    private static final class FruitProvider extends TestParameterValuesProvider {\n      @Override\n      public List\u003c?\u003e provideValues(Context context) {\n        return ImmutableList.of(\n            value(new Apple()).withName(\"apple\"),\n            value(new Banana()).withName(\"banana\"));\n      }\n    }\n    ```\n\n-   The given `Context` contains the test class and other annotations on the\n    `@TestParameter`-annotated parameter/field. This allows more generic\n    providers that take into account custom annotations with extra data, or the\n    implementation of abstract methods on a base test class.\n\n### Dynamic parameter generation for `@TestParameters`\n\nInstead of providing a YAML mapping of parameters, you can implement your own\n`TestParametersValuesProvider` as follows:\n\n```java\nimport com.google.testing.junit.testparameterinjector.TestParametersValuesProvider;\nimport com.google.testing.junit.testparameterinjector.TestParameters.TestParametersValues;\n\n@Test\n@TestParameters(valuesProvider = IsAdultValueProvider.class)\npublic void personIsAdult(int age, boolean expectIsAdult) { ... }\n\nstatic final class IsAdultValueProvider extends TestParametersValuesProvider {\n  @Override public ImmutableList\u003cTestParametersValues\u003e provideValues(Context context) {\n    return ImmutableList.of(\n      TestParametersValues.builder()\n        .name(\"teenager\")\n        .addParameter(\"age\", 17)\n        .addParameter(\"expectIsAdult\", false)\n        .build(),\n      TestParametersValues.builder()\n        .name(\"young adult\")\n        .addParameter(\"age\", 22)\n        .addParameter(\"expectIsAdult\", true)\n        .build()\n    );\n  }\n}\n```\n","funding_links":[],"categories":["测试","Java"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogle%2FTestParameterInjector","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgoogle%2FTestParameterInjector","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogle%2FTestParameterInjector/lists"}