Issue
Say I have a @BeforeEach
method which uses an external method to get a value and set something up with said value:
@BeforeEach
void foo() {
int bar = getBarFromSomething();
setupSomethingWithBar(bar);
}
Now, I want to be able to pass the value of bar
(which may change every time getBarFromSomething()
is called) to each individual test case after the foo()
method is called before the test case. I want to do this so that I can test something using the parameter which I setup in the @BeforeEach foo()
method call:
@Test
void test_baz(int bar) {
assertEquals(bar, 5);
}
How would I go about passing a parameter from the @BeforeEach foo()
call to each individual @Test
case? I don't think that parameterized tests will work since the method which generates bar
may output different results so it needs to be called only once per @BeforeEach
and @Test
case run and it needs to be used to set something up in the foo()
call.
Solution
Just move the method variable to a member variable... like this:
int bar = getBarFromSomething();
@BeforeEach
void foo() {
setupSomethingWithBar(bar);
}
Then
@Test
void test_baz() {
assertEquals(bar, 5);
}
Should work
Answered By - Bill K