使用登录测试到其他测试的数据结果



我需要访问由securityEtest.login在另一个类用户中成功登录提供的令牌,以获取标题中的承载值。在哪里存储通过登录生成的令牌的最佳场所,因此可以通过其他测试(在班级或外部或外部)访问

baseitest

@AutoConfigureMockMvc
@SpringBootTest(classes = Application.class)
public class BaseITest extends AbstractTestNGSpringContextTests {
    @Autowired
    protected MockMvc mvc;
    @Autowired
    ObjectMapper mapper;
}

SecurityIitest

public class SecurityIITest extends BaseITest {
    @Value("${bootstrap.username}")
    private String username;
    @Value("${bootstrap.password}")
    private String password;
    @BeforeSuite(groups = {"security"})
    public void login() throws Exception {
        String jsonResult = mvc.perform(post(ApiUrls.LOGIN)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("username", username)
                .param("password", password))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath(JsonField.TOKEN).exists())
                .andReturn().getResponse().getContentAsString();
        JsonNode result = mapper.readTree(jsonResult);
        // this token to reuse in other methods from other class
        // token = result.get("token").asText();
    }
}

accountControllerItest

public class AccountControllerITest extends BaseITest {
   @Test(dependsOnGroups = {"security"})
    public void postAccount() throws Exception {
        // need to access token here
    }
}

如果测试在同一<test>标签之内,则可以通过以下方式跨多个@Test方法共享数据

设置数据

Object object = new Object();
Reporter.getCurrentTestResult().getTestContext().setAttribute("foo", object);

获取数据

Object obj = Reporter.getCurrentTestResult().getTestContext().getAttribute("foo");

@Test方法中。

如果测试在不同的<test>标签之内,但是在同一<suite>中,则可以通过调用

共享数据

设置数据

Object object = new Object();
Reporter.getCurrentTestResult().getTestContext().getSuite().setAttribute("foo", object);

获取数据

Object obj = Reporter.getCurrentTestResult().getTestContext().getSuite().getAttribute("foo");

@Test方法中。

最新更新