Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between / advantage of using JUnit 5's @ParametrizedTest over @TestFactory Stream<DynamicTest>?

Tags:

First, what do they mean by this in the conclusion of Guide to Dynamic Tests in Junit 5?

The parameterized tests can replace many of the examples in this article. However, the dynamic tests differ from the parameterized tests as they support full test lifecycle, while parametrized tests don’t.

I skimmed through JUnit 5 – Parameterized Tests and believe I understand the differences at a syntactic level, and also believe I get this:

Moreover, dynamic tests provide more flexibility regarding how the input is generated and how the tests are executed.

But then it seems like, why would anyone prefer parametrized tests over dynamic tests?

like image 818
slackwing Avatar asked Feb 28 '19 09:02

slackwing


1 Answers

Dynamic tests, I refer to them as testlets, are just soft/grouped-assertions (assertAll(...)) on steroids. You'll see an entry for each generated dynamic test in the reports but they are not real tests.

The quote (from baeldung) your copied into your question is wrong. It should read as in JUnit's User-Guide:

Dynamic Test Lifecycle

The execution lifecycle of a dynamic test is quite different than it is for a standard @Test case. Specifically, there are no lifecycle callbacks for individual dynamic tests. This means that @BeforeEach and @AfterEach methods and their corresponding extension callbacks are executed for the @TestFactory method but not for each dynamic test.

For more details read: https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests

Why would anyone prefer parametrized tests over dynamic tests?

  1. If you need full lifecyle support for each test (template invocation).
  2. If you want to declare your arguments in annotations.

Find a lot more details on how to provide arguments in various forms to a @ParameterizedTest here: https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests -- mind that "class/container templates" are slated for a later release: https://github.com/junit-team/junit5/issues/878

I wrote a blog post comparing 5 steps of scattering 3 assertions with JUnit Jupiter here: https://sormuras.github.io/blog/2018-05-14-junit5-scatter-assertions.html enter image description here

like image 83
Sormuras Avatar answered Oct 19 '22 03:10

Sormuras