springmockmvc测试怪异的行为单一与“全部”执行

mqxuamgl  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(230)

我目前遇到一个奇怪的问题,关于junit测试中spring的mockmvc与Spring Security 的结合。
当我运行整个类的测试时,一切正常,测试通过。但是当我运行项目中的所有测试时,一个测试总是在某个类中失败,如果我删除失败的测试方法也没关系,那么另一个测试在同一个类中失败。

@SpringBootTest
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
class AuthenticationApiTest {
    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;
    private static ObjectMapper objectMapper;

    @BeforeAll
    static void beforeAll() {
        objectMapper = new ObjectMapper();
    }

    @BeforeEach
    void setUp(RestDocumentationContextProvider documentation) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
                .apply(documentationConfiguration(documentation)
                        .operationPreprocessors()
                        .withRequestDefaults(prettyPrint(),removeHeaders("Content-Length","Host","Pragma","X-XSS-Protection","Expires","X-Frame-Options","X-Content-Type-Options","Cache-Control"))
                        .withResponseDefaults(prettyPrint(),removeHeaders("Content-Length","Host","Pragma","X-XSS-Protection","Expires","X-Frame-Options","X-Content-Type-Options","Cache-Control")))
                .apply(springSecurity())
                .build();
    }

失败的测试:

@Test
    public void testSignUpFail() throws Exception {
        SignUpBody signUpBody = new SignUpBody();
        signUpBody.setPassword("demo1234");
        signUpBody.setFirstname("first");
        signUpBody.setLastname("lastn");

        this.mockMvc.perform(post("/auth/user/signup")
                .header(HttpHeaders.CONTENT_TYPE,"application/json")
                .content(objectMapper.writeValueAsString(signUpBody))
        ).andExpect(status().is(400))
                .andDo(document("user-signup-fail"));

        this.mockMvc.perform(post("/auth/vendor/signup")
                .header(HttpHeaders.CONTENT_TYPE,"application/json")
                .content(objectMapper.writeValueAsString(signUpBody))
        ).andExpect(status().is(400))
                .andDo(document("vendor-signup-fail"));
    }

对如何解决这个奇怪的问题有什么建议吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题