Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,129 @@ public class CalculatorTest {
}
```

## `@WithBooleanParams` — true / false shorthand

Runs the test twice: once with `true` and once with `false`. No need to list the values manually.

```java
@Test
@WithBooleanParams
public void toggleFeature() {
boolean enabled = params.asBoolean();
feature.setEnabled(enabled);
assertEquals(enabled, feature.isEnabled());
}
```

## `@WithNullParam` — null-safety testing

Runs the test twice: once with the provided non-null value and once with `null`.
Ideal for verifying that your code handles `null` inputs gracefully.

```java
@Test
@WithNullParam("hello")
public void handlesNull() {
String value = params.get(); // "hello" on the first run, null on the second
processValue(value); // must not throw for either case
}
```

Use the optional `name` attribute for named parameters:

```java
@Test
@WithNullParam(value = "hello", name = "input")
public void handlesNullNamed() {
String value = params.get("input");
}
```

## `@WithEnumParams` — iterate over all enum constants

Automatically runs the test once for every constant in the specified enum class.
The current constant is retrieved via the type-safe `asEnum(Class)` accessor.

```java
enum Color { RED, GREEN, BLUE }

@Test
@WithEnumParams(Color.class)
public void testAllColors() {
Color color = params.asEnum(Color.class);
assertNotNull(color);
renderBackground(color); // called for RED, GREEN, and BLUE
}
```

Use the optional `name` attribute for named parameters:

```java
@Test
@WithEnumParams(value = Color.class, name = "color")
public void testAllColorsNamed() {
Color color = params.asEnum("color", Color.class);
assertNotNull(color);
}
```

## `@WithParamsSource` — method-provided parameter sets

Reads parameter sets from a static method in the test class.
Avoids large annotation arrays and keeps complex data sets as real Java code.

The provider method must be `static`, accept no arguments, and return `String[][]`
where each inner array is one test iteration. The `names` attribute maps column
indices to parameter names.

```java
@Test
@WithParamsSource(value = "provideNumbers", names = {"n1", "n2", "result"})
public void sum() {
int n1 = params.asInt("n1");
int n2 = params.asInt("n2");
assertEquals(params.asInt("result"), calculator.sum(n1, n2));
}

static String[][] provideNumbers() {
return new String[][] {
{"1", "2", "3"},
{"11", "-2", "9"}
};
}
```

Single-parameter shorthand (default name `"param1"`):

```java
@Test
@WithParamsSource("provideWords")
public void wordIsNotEmpty() {
String word = params.get();
assertFalse(word.isEmpty());
}

static String[][] provideWords() {
return new String[][] { {"hello"}, {"world"}, {"foo"} };
}
```

## `asEnum(Class)` — type-safe enum accessor

Converts the current string parameter value to an enum constant by name.
Returns `null` if the stored value is `null` (e.g. when used with `@WithNullParam`).

```java
// default parameter
Color color = params.asEnum(Color.class);

// named parameter
Color color = params.asEnum("colorParam", Color.class);
```

The accessor works with any enum and complements the existing typed accessors
(`asInt()`, `asBoolean()`, `asDouble()`, etc.).

## Kotlin

Kotlin is supported, with some small differences.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/**
* The MIT License
* <p>
* Copyright (c) 2017, Ignacio Tomas Crespo (itcrespo@gmail.com)
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.ignaciotcrespo.junitwithparams;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Parameterised test annotation that automatically iterates over every constant of an
* enum class. This eliminates the need to list each enum value as a string in
* {@link WithParams}, and keeps tests resilient to future enum additions.
*
* <p>Each enum constant is stored by its {@link Enum#name()} and can be retrieved in
* the test body via {@link WithParamsRule#asEnum(Class)}.
*
* <h3>Example</h3>
* <pre>
* enum Color { RED, GREEN, BLUE }
*
* {@literal @}Test
* {@literal @}WithEnumParams(Color.class)
* public void testAllColors() {
* Color color = params.asEnum(Color.class);
* assertNotNull(color);
* }
* </pre>
*
* <h3>Named-parameter example</h3>
* <pre>
* {@literal @}Test
* {@literal @}WithEnumParams(value = Color.class, name = "color")
* public void testAllColorsNamed() {
* Color color = params.asEnum("color", Color.class);
* }
* </pre>
*
* @see WithParamsRule#asEnum(Class)
* @see WithParamsRule#asEnum(String, Class)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface WithEnumParams {

/**
* The enum class whose constants will be iterated.
*
* @return the enum class
*/
Class<? extends Enum<?>> value();

/**
* The parameter name used to retrieve the current constant in the test body via
* {@link WithParamsRule#asEnum(Class)} or {@link WithParamsRule#asEnum(String, Class)}.
* Defaults to {@code "param1"}.
*
* @return the parameter name
*/
String name() default "param1";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* The MIT License
* <p>
* Copyright (c) 2017, Ignacio Tomas Crespo (itcrespo@gmail.com)
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.ignaciotcrespo.junitwithparams;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Parameterised test annotation that runs the test twice: once with the provided
* non-null string value and once with {@code null}.
*
* <p>This is useful for null-safety testing — it ensures that code handles both a
* valid value and {@code null} without requiring you to write two separate tests.
*
* <h3>Single-parameter example</h3>
* <pre>
* {@literal @}Test
* {@literal @}WithNullParam("hello")
* public void handlesNull() {
* String value = params.get(); // "hello" on first run, null on second
* // assert whatever makes sense for both cases
* }
* </pre>
*
* <h3>Named-parameter example</h3>
* <pre>
* {@literal @}Test
* {@literal @}WithNullParam(value = "hello", name = "input")
* public void handlesNullNamed() {
* String value = params.get("input");
* }
* </pre>
*
* @see WithParamsRule#get()
* @see WithBooleanParams
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface WithNullParam {

/**
* The non-null value to inject on the first test iteration.
*
* @return the string value
*/
String value();

/**
* The parameter name used to retrieve the value in the test body via
* {@link WithParamsRule#get(String)}. Defaults to {@code "param1"}.
*
* @return the parameter name
*/
String name() default "param1";
}
Loading
Loading