下面列出了org.springframework.http.converter.FormHttpMessageConverter#org.springframework.test.web.servlet.setup.MockMvcBuilders 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings( "rawtypes" )
@Before
public void setUp() throws Exception{
when(jobDao.getJobRuns(null, AgentConsumer.LIMIT_JOB_RUNS)).thenReturn(
new ConcurrentSkipListMap<Long, CallableJob>());
agentDriver = new AgentDriver(jobDao, reporting);
agentConsumer =
spy(new AgentConsumer(jobDao, reporting, "testing.hostname.com",
new MailInfo("", "", "", ""),
Session.getDefaultInstance(new Properties()),
drivers, 10, numOfConcurrentReruns, maxReruns, 60, 1));
controller = new ChronosController(jobDao, agentDriver, agentConsumer, drivers, folder.getRoot().getPath());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ChronosMapper());
HttpMessageConverter[] messageConverters =
new HttpMessageConverter[] {converter};
this.mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(messageConverters).build();
}
@Test
@Transactional
public void getAllPoints() throws Exception {
// Initialize the database
pointsRepository.saveAndFlush(points);
// Create security-aware mockMvc
restPointsMockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
// Get all the pointsList
restPointsMockMvc.perform(get("/api/points?sort=id,desc")
.with(user("admin").roles("ADMIN")))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(points.getId().intValue())))
.andExpect(jsonPath("$.[*].date").value(hasItem(DEFAULT_DATE.toString())))
.andExpect(jsonPath("$.[*].exercise").value(hasItem(DEFAULT_EXERCISE)))
.andExpect(jsonPath("$.[*].meals").value(hasItem(DEFAULT_MEALS)))
.andExpect(jsonPath("$.[*].alcohol").value(hasItem(DEFAULT_ALCOHOL)))
.andExpect(jsonPath("$.[*].notes").value(hasItem(DEFAULT_NOTES.toString())));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/test/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@BeforeEach
public void beforeEach() {
CustomerController controller = new CustomerController(userAccountService, orderService, authenticationService, cartService, productService);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.addInterceptors(new SessionCartInterceptor())
.setViewResolvers(new InternalResourceViewResolver("/WEB-INF/view/", ".jsp"))
.build();
Contacts contacts = FixturesFactory.contacts().build();
account = FixturesFactory.account()
.setContacts(contacts)
.build();
principal = new PrincipalImpl(account.getEmail());
Region region = FixturesFactory.region().build();
Distillery distillery = FixturesFactory.distillery(region).build();
product = FixturesFactory.product(distillery).build();
order = FixturesFactory.order(account).build();
orderedProduct = FixturesFactory.orderedProduct(order, product).build();
order.setOrderedProducts(Collections.singleton(orderedProduct));
Bill bill = FixturesFactory.bill(order).build();
order.setBill(bill);
cart = new Cart.Builder()
.setId(account.getId())
.setUserAccount(account)
.build();
}
@BeforeEach
public void beforeEach() {
OrdersController controller = new OrdersController(orderService, properties);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setViewResolvers(new InternalResourceViewResolver("/WEB-INF/view/", ".jsp"))
.build();
Region region = FixturesFactory.region().build();
Distillery distillery = FixturesFactory.distillery(region).build();
product = FixturesFactory.product(distillery).build();
UserAccount userAccount = FixturesFactory.account().build();
userAccount.setContacts(FixturesFactory.contacts().build());
order = FixturesFactory.order(userAccount).build();
totalOrders = Collections.singletonList(order);
orderedProduct = FixturesFactory.orderedProduct(order, product).build();
order.setOrderedProducts(Collections.singleton(orderedProduct));
Bill bill = FixturesFactory.bill(order).build();
order.setBill(bill);
}
@Test
@Transactional
public void getAllPreferences() throws Exception {
// Initialize the database
preferencesRepository.saveAndFlush(preferences);
// create security-aware mockMvc
restPreferencesMockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
// Get all the preferencesList
restPreferencesMockMvc.perform(get("/api/preferences?sort=id,desc")
.with(user("admin").roles("ADMIN")))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(preferences.getId().intValue())))
.andExpect(jsonPath("$.[*].weeklyGoal").value(hasItem(DEFAULT_WEEKLY_GOAL)))
.andExpect(jsonPath("$.[*].weightUnits").value(hasItem(DEFAULT_WEIGHT_UNITS.toString())));
}
@SuppressWarnings({"unchecked"})
public void getAllPostsWithEagerRelationshipsIsEnabled() throws Exception {
PostResource postResource = new PostResource(postRepositoryMock);
when(postRepositoryMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
MockMvc restPostMockMvc = MockMvcBuilders.standaloneSetup(postResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
restPostMockMvc.perform(get("/api/posts?eagerload=true"))
.andExpect(status().isOk());
verify(postRepositoryMock, times(1)).findAllWithEagerRelationships(any());
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/test/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Before
public void setup() {
final String fakeSalt = cryptSaltFactory.generateSalt(FAKE_PASSWORD);
final Consumer<Long> fakeTimeSetter = TestHelper.mockOutCurrentTimeProvider(mockCurrentTimeProvider);
fakeTimeSetter.accept(FROZEN_TIME.toEpochMilli());
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
when(passwordGenerator.generateCredential(any(GenerationParameters.class)))
.thenReturn(new StringCredentialValue(FAKE_PASSWORD));
when(certificateGenerator.generateCredential(any(GenerationParameters.class)))
.thenReturn(new CertificateCredentialValue(CA, CERTIFICATE, CERTIFICATE_PRIVATE_KEY, null, false, false, true, false));
when(sshGenerator.generateCredential(any(GenerationParameters.class)))
.thenReturn(new SshCredentialValue(PUBLIC_KEY, PRIVATE_KEY, null));
when(rsaGenerator.generateCredential(any(GenerationParameters.class)))
.thenReturn(new RsaCredentialValue(RSA_PUBLIC_KEY, RSA_PRIVATE_KEY));
when(userGenerator.generateCredential(any(GenerationParameters.class)))
.thenReturn(new UserCredentialValue(USERNAME, FAKE_PASSWORD, fakeSalt));
}
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
AuditEventService auditEventService =
new AuditEventService(auditEventRepository, auditEventConverter);
AuditResource auditResource = new AuditResource(auditEventService);
this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setConversionService(formattingConversionService)
.setMessageConverters(jacksonMessageConverter).build();
}
@Test
public void handleEnvironmentException() throws Exception {
when(repository.findOne(eq("exception"), eq("bad-syntax.ext"), any(), eq(false)))
.thenThrow(new FailedToConstructEnvironmentException("Cannot construct",
new RuntimeException("underlier")));
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(controller).build();
MvcResult result = mvc
.perform(MockMvcRequestBuilders.get("/exception/bad-syntax.ext"))
.andExpect(MockMvcResultMatchers.status().is(500)).andReturn();
assertThat(result.getResponse().getErrorMessage()).isEqualTo("Cannot construct");
}
@Before
public void setupMocks() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON)).build();
for (AppRegistration appRegistration : this.appRegistryService.findAll()) {
this.appRegistryService.delete(appRegistration.getName(), appRegistration.getType(), appRegistration.getVersion());
}
this.uriRegistryPopulator.afterPropertiesSet();
this.skipperClient = MockUtils.configureMock(this.skipperClient);
}
@Before
public void setup() {
//remove::start[]
RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(document(getClass().getSimpleName() + "_" + this.testName.getMethodName()))
.build());
//remove::end[]
}
@PostConstruct
public void setup() {
MockitoAnnotations.initMocks(this);
BookResource bookResource = new BookResource();
ReflectionTestUtils.setField(bookResource, "bookRepository", bookRepository);
this.restBookMockMvc = MockMvcBuilders.standaloneSetup(bookResource).build();
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Before
public void setup() {
LogsResource logsResource = new LogsResource();
this.restLogsMockMvc = MockMvcBuilders
.standaloneSetup(logsResource)
.build();
}
@BeforeEach
public void setup() {
cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).clear();
cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE).clear();
UserResource userResource = new UserResource(userService);
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter)
.build();
}
@Test
public void mergeParameter() throws Exception {
String paramName = "PARENT";
String paramValue = "VALUE";
String paramValue2 = "VALUE2";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").param(paramName, paramValue, paramValue2))
.build();
MockHttpServletRequest performedRequest = mockMvc.perform(requestBuilder).andReturn().getRequest();
assertThat(asList(performedRequest.getParameterValues(paramName)), contains(paramValue, paramValue2));
}
@Before
public void setup() {
SecurityContextHolder.clearContext();
AccountResource control = new AccountResource();
this.mock = MockMvcBuilders.standaloneSetup(control)
.setControllerAdvice(new ExceptionTranslator())
.build();
}
@Before
public void beforeEach() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
@Before
public void setUp() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
@Before
public void setup() {
ResourceBundleViewResolver viewResolver = new ResourceBundleViewResolver();
viewResolver.setBasename("config.views");
mockMvc = MockMvcBuilders.standaloneSetup(new AdminController()).
setViewResolvers(viewResolver).build();
}
@PostConstruct
public void setup() {
MockitoAnnotations.initMocks(this);
RaceResultResource raceResultResource = new RaceResultResource();
ReflectionTestUtils.setField(raceResultResource, "raceResultRepository", raceResultRepository);
this.restRaceResultMockMvc = MockMvcBuilders.standaloneSetup(raceResultResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setMessageConverters(jacksonMessageConverter).build();
}
@Before
public void init() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(datasourceController)
/* .addFilters(new CORSFilter()) */
.build();
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
TagResource tagResource = new TagResource(tagRepository, tagSearchRepository);
this.restTagMockMvc = MockMvcBuilders.standaloneSetup(tagResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
final YoRCResource yoRCResource = new YoRCResource(yoRCService);
this.restYoRCMockMvc = MockMvcBuilders.standaloneSetup(yoRCResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
@PostConstruct
public void setup() {
MockitoAnnotations.initMocks(this);
SensorResource sensorResource = new SensorResource();
ReflectionTestUtils.setField(sensorResource, "sensorRepository", sensorRepository);
this.restSensorMockMvc = MockMvcBuilders.standaloneSetup(sensorResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setMessageConverters(jacksonMessageConverter).build();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
options("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"))
.andExpect(header().string(HttpHeaders.VARY, "Origin"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}