Skip to content

MockitoTestExecutionListener no longer opens mocks in the prepareTestInstance() callback #33690

Closed as not planned
@wilkinsona

Description

@wilkinsona

Affects: 6.2.0-SNAPSHOT

This is a recent regression from 6.2.0-RC1. I believe it was introduced in eb4bf1c#diff-02b9cc5ba2d6121e1a5f63ad339bb82fa8f3531d568c43d07fac61ade962c0cd where the override of prepareTestInstance was removed. The result is that trying to call a @Mock-annotated field in a @BeforeAll method fails with an NPE.

This should reproduce the regression:

package com.example;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;

import java.util.List;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
class MockInitInBeforeAllTests {
	
	@Mock
	private static List<String> mock;

	@BeforeAll
	static void setUp() {
		given(mock.size()).willReturn(1);
	}

	@Test
	void shouldSetUpSuccessfully() {
		assertThat(mock.size()).isEqualTo(1);
	}

}

Another, more advanced variant that uses a custom test instance lifecycle and which is closer to the Spring Boot test that found the regression also fails with 6.2.0-SNAPSHOT:

package com.example;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;

import java.util.List;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@TestInstance(Lifecycle.PER_CLASS)
@ExtendWith(SpringExtension.class)
class MockInitInBeforeAllTests {
	
	@Mock
	private List<String> mock;

	@BeforeAll
	void setUp() {
		given(this.mock.size()).willReturn(1);
	}

	@Test
	void shouldSetUpSuccessfully() {
		assertThat(mock.size()).isEqualTo(1);
	}

}

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulestatus: supersededAn issue that has been superseded by anothertype: regressionA bug that is also a regression

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions