【问题标题】:Only first test in class failed when running multiple classes运行多个类时,只有类中的第一个测试失败
【发布时间】:2020-11-12 23:47:59
【问题描述】:

在 intellij 中运行多个测试时,我遇到了一个非常奇怪的问题。我在课堂上的第一次测试失败了,因为显然 jwt 无效,但是在同一个班级的第二次测试中,使用相同的 jwt 一切正常。

如果我尝试分别运行每个类,一切正常,如果我从终端运行mvn test,所有测试都会通过。

This is my configuration for the test in intellij

我也尝试将Fork mode设置为class,然后测试通过,但是每个测试都是单独运行的,所以需要一段时间,而且我不能在Fork mode中使用覆盖率。

编辑: 这是我的初始化代码和第一次测试

    @BeforeAll
    void init() throws Exception {
        token = login(new LoginRequest("user", "123"));
    }

    private String login(LoginRequest loginRequest) throws Exception {
        ResultActions resultActions = mockMvc.perform(post("/api/auth/login")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(loginRequest)))
                .andExpect(status().isOk());
        return resultActions.andReturn().getResponse().getHeader(JwtUtilities.HEADER);
    }

    @Test
    @Order(1)
    void findAllTeamsByCreator_ok() throws Exception {
        mockMvc.perform(get(PATH)
                .contentType(MediaType.APPLICATION_JSON)
                .header(JwtUtilities.HEADER, token))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/hal+json"))
                .andExpect(jsonPath("$._embedded.teamDtoList").isNotEmpty());
    }

所以,我没有在我的测试中设置任何状态,如果我创建这样的测试

@Test
@Order(1)
void test() {}

然后其他一切都保持不变,我的测试将起作用。就像在第一次测试中没有加载某些东西一样。

我真的很奇怪为什么mvn test 工作正常,但在 Intellij 中我有错误

【问题讨论】:

    标签: java spring-boot junit


    【解决方案1】:

    这听起来像是您的测试用例中的“状态已满”,所以第一个测试中的某些东西正在初始化其余测试用例中需要的东西。

    当您使用 JUnit 时,您可能会确保所有初始化都在框架支持的“Before”类型方法之一中完成。

    查看您的第一个测试用例的代码以确定什么具有“状态”会很有帮助。

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多