2017-09-21 55 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方法。