Skip to content
Advertisement

Spring Mockito @BeforeAll mocking logic works on 1 test only

I have a problem with understanding why the logic mocked inside @BeforeAll works, but only for the first test. They work fine separately, copying the identical logic to both tests will produce the same result – 1 passed, 1 failed. What happens: in AboutUsService.update() on the first line appears the mistake at

pageRepository.getByName(ABOUT_US_PAGE).orElseThrow(null);

For the first test, the calling of the method produces the expected result and returns AboutUsPage with its data. But for the next one it produces Optional.empty and NullPointerException eventually. What is the trick, why mocking works only for one test? Also, I checked out if the real repository is getting called, but it seems like something else caused it. Changing the annotation to @BeforeEach solves this problem, but shouldn’t it work as well with @BeforeAll? Spring Boot v. 2.3.4

JavaScript

Advertisement

Answer

@BeforeAll is executed once, before any test is executed. If you need logic that is executed before every test, use @Before

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement