Skip to content

Commit 485832c

Browse files
committed
Test multiple implementations using ArgumentsProvider
1 parent f27f24d commit 485832c

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package io.mincong.junit5;
2+
3+
public interface ChatBot {
4+
String sayHello(String username);
5+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package io.mincong.junit5;
2+
3+
public class StringConcatenationChatBot implements ChatBot {
4+
5+
@Override
6+
public String sayHello(String username) {
7+
return "Hello, " + username;
8+
}
9+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package io.mincong.junit5;
2+
3+
public class StringFormatChatBot implements ChatBot {
4+
@Override
5+
public String sayHello(String username) {
6+
return String.format("Hello, %s", username);
7+
}
8+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package io.mincong.junit5;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import java.util.stream.Stream;
6+
import org.junit.jupiter.api.extension.ExtensionContext;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.Arguments;
9+
import org.junit.jupiter.params.provider.ArgumentsProvider;
10+
import org.junit.jupiter.params.provider.ArgumentsSource;
11+
12+
class ChatBotTest {
13+
/**
14+
* Use annotation {@link ParameterizedTest} to test multiple implementation of {@link ChatBot}. It
15+
* ensures that all implementations respect the specification of the interface and returns the
16+
* expected results regardless the internal implementation.
17+
*
18+
* @param bot the chat bot to test
19+
*/
20+
@ParameterizedTest
21+
@ArgumentsSource(ChatBotProvider.class)
22+
void sayHello(ChatBot bot) {
23+
assertThat(bot.sayHello("Foo")).isEqualTo("Hello, Foo");
24+
assertThat(bot.sayHello("Bar")).isEqualTo("Hello, Bar");
25+
}
26+
27+
public static class ChatBotProvider implements ArgumentsProvider {
28+
29+
/**
30+
* This method creates multiple chat bot instances using different implementations and returns
31+
* them as a stream of arguments for the parameterized test.
32+
*/
33+
@Override
34+
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
35+
return Stream.of(new StringFormatChatBot(), new StringConcatenationChatBot())
36+
.map(Arguments::of);
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)