Junit 平台 v.5.8.1 java.lang.NoSuchMethodError 出现错误:org.junit.platform.commons.util.AnnotationUtils.findAnnotation

Vol*_*myr 7 java spring-mvc spring-test junit5

我遇到了此代码的问题:

@ExtendWith(MockitoExtension.class)
class ApiRestControllerTest {

  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  private MockMvc mockMvc;

  @InjectMocks
  private ApiRestController apiRestController;

  @BeforeEach
  void setUp() {
    mockMvc = MockMvcBuilders
        .standaloneSetup(apiRestController)
        .build();
  }

  @Test
  void shouldReturnsVersion() throws Exception {
    mockMvc.perform(get("/api/v1/version"))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(content().json(OBJECT_MAPPER.writeValueAsString(new VersionResponse(VERSION))));
  }
} 
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

@ExtendWith(MockitoExtension.class)
class ApiRestControllerTest {

  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  private MockMvc mockMvc;

  @InjectMocks
  private ApiRestController apiRestController;

  @BeforeEach
  void setUp() {
    mockMvc = MockMvcBuilders
        .standaloneSetup(apiRestController)
        .build();
  }

  @Test
  void shouldReturnsVersion() throws Exception {
    mockMvc.perform(get("/api/v1/version"))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(content().json(OBJECT_MAPPER.writeValueAsString(new VersionResponse(VERSION))));
  }
} 
Run Code Online (Sandbox Code Playgroud)

我使用 JUnit 5.8.1,但对于较低版本,如 5.7.2 ,它工作正常,

Sam*_*nen 7

org.junit.platform.commons.util.AnnotationUtils.findAnnotation(Class<?>, Class<A>, boolean)JUnit Platform 1.8 中引入了缺少的方法。

因此,您需要确保升级到junit-platform-commons1.8.1。

使用junit-bom将有助于简化此类升级,以确保您使用所有 JUnit 5 工件的兼容版本。

  • 谢谢你为我做的。将此注释留给其他潜在读者:我的父 Maven 项目依赖管理分别指定了 `org.junit.jupiter:junit-jupiter-engine` 和 `org.junit.jupiter:junit-jupiter-api`。更改为“org.junit:junit-bom”,错误消失了。[示例项目](https://github.com/junit-team/junit5-samples/blob/main/junit5-jupiter-starter-maven/pom.xml)应该是一个很好的参考。 (4认同)