1
我一直在爲我們的Spring MVC應用程序編寫集成測試。我們使用oAuth2進行身份驗證。Java Spring MVC集成測試創建OAuth2校長
在這種情況下,Spring會給我們一個Principal
實例,我們用它來確定我們必須發送回客戶端的實體。在我們的控制,我們有一個端點:
@RequestMapping("/bookings")
public @ResponseBody ResponseEntity<List<ThirdPartyBooking>> getBookings(Principal principal) {
OAuth2Authentication auth = (OAuth2Authentication) principal;
OAuth2AuthenticationDetails authDetails = (OAuthAuthenticationDetails) auth.getDetails();
// Extract stuff from the details...
}
現在,在我們的測試中,我想確保我們只發送預訂已認證用戶。下面的測試代碼,可以發現:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {ThirdPartyBookingServiceConfiguration.class})
@WebAppConfiguration
@Component
public abstract class RepositoryTestBase {
@Resource
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void shouldOnlyReturnUserBookings() throws Exception {
MockHttpServletResponse result = mockMvc.perform(MockMvcRequestBuilders.get("/bookings").principal(???)).andReturn().getResponse();
// Validate the response
}
}
我怎麼會插入一個OAuth2Authentication
在???
?
這不正是我一直在尋找。它的確有很大的幫助。謝謝! – irundaia