2017-09-21 76 views
0

我需要访问标头中承载值的另一个类用户的SecurityITest.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

0123跨多个 @Test方法个

回答

1

如果测试是相同的<test>标签内,那么你可以共享数据是它的一部分,通过:

要设置数据

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

获取数据

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

from within一种@Test方法。

如果测试不同<test>标签内,但同样<suite>内,那么你可以通过调用

要设置数据

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

获取数据

Object obj = Reporter.getCurrentTestResult().getTestContext().getSuite().getAttribute("foo"); 
共享数据

from @Test方法。