org.springframework.test.web.servlet.setup.MockMvcBuilders Java Examples

The following examples show how to use org.springframework.test.web.servlet.setup.MockMvcBuilders. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: chronos   Author: aolarchive   File: TestChronosController.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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();
}
 
Example #2
Source Project: 21-points   Author: mraible   File: PointsResourceIntTest.java    License: Apache License 2.0 6 votes vote down vote up
@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())));
}
 
Example #3
Source Project: 21-points   Author: mraible   File: WebConfigurerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #4
Source Project: market   Author: aleksey-lukyanets   File: CustomerControllerTest.java    License: MIT License 6 votes vote down vote up
@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();
}
 
Example #5
Source Project: market   Author: aleksey-lukyanets   File: OrdersControllerTest.java    License: MIT License 6 votes vote down vote up
@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);
}
 
Example #6
Source Project: 21-points   Author: mraible   File: PreferencesResourceIntTest.java    License: Apache License 2.0 6 votes vote down vote up
@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())));
}
 
Example #7
Source Project: java-microservices-examples   Author: oktadeveloper   File: PostResourceIT.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #8
Source Project: e-commerce-microservice   Author: xebialabs   File: WebConfigurerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #9
Source Project: credhub   Author: cloudfoundry-incubator   File: CredentialsTypeSpecificGenerateIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #10
Source Project: java-microservices-examples   Author: oktadeveloper   File: AuditResourceIT.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #11
Source Project: spring-cloud-config   Author: spring-cloud   File: EnvironmentControllerTests.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #12
Source Project: spring-cloud-dataflow   Author: spring-cloud   File: AppRegistryControllerTests.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #13
Source Project: spring-cloud-contract-samples   Author: spring-cloud-samples   File: BeerIntoxicationBase.java    License: Apache License 2.0 5 votes vote down vote up
@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[]
}
 
Example #14
Source Project: angularjs-springboot-bookstore   Author: josedab   File: BookResourceTest.java    License: MIT License 5 votes vote down vote up
@PostConstruct
public void setup() {
    MockitoAnnotations.initMocks(this);
    BookResource bookResource = new BookResource();
    ReflectionTestUtils.setField(bookResource, "bookRepository", bookRepository);
    this.restBookMockMvc = MockMvcBuilders.standaloneSetup(bookResource).build();
}
 
Example #15
Source Project: albedo   Author: somowhere   File: WebConfigurerTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@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));
}
 
Example #16
Source Project: e-commerce-microservice   Author: xebialabs   File: LogsResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    LogsResource logsResource = new LogsResource();
    this.restLogsMockMvc = MockMvcBuilders
        .standaloneSetup(logsResource)
        .build();
}
 
Example #17
Source Project: java-microservices-examples   Author: oktadeveloper   File: UserResourceIT.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #18
Source Project: java-technology-stack   Author: codeEngraver   File: HtmlUnitRequestBuilderTests.java    License: MIT License 5 votes vote down vote up
@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));
}
 
Example #19
Source Project: jhipster-microservices-example   Author: oktadeveloper   File: ExceptionTranslatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    SecurityContextHolder.clearContext();
    AccountResource control = new AccountResource();
    this.mock = MockMvcBuilders.standaloneSetup(control)
        .setControllerAdvice(new ExceptionTranslator())
        .build();
}
 
Example #20
Source Project: credhub   Author: cloudfoundry-incubator   File: CredentialFindTestNoAcls.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void beforeEach() {
  mockMvc = MockMvcBuilders
    .webAppContextSetup(webApplicationContext)
    .apply(springSecurity())
    .build();
}
 
Example #21
Source Project: credhub   Author: cloudfoundry-incubator   File: CredentialSetErrorHandlingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  mockMvc = MockMvcBuilders
    .webAppContextSetup(webApplicationContext)
    .apply(springSecurity())
    .build();
}
 
Example #22
Source Project: Spring-MVC-Blueprints   Author: PacktPublishing   File: ViewReportsTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() {
    ResourceBundleViewResolver viewResolver = new ResourceBundleViewResolver();
    viewResolver.setBasename("config.views");
  
 
    mockMvc = MockMvcBuilders.standaloneSetup(new AdminController()).
    		setViewResolvers(viewResolver).build();
}
 
Example #23
Source Project: gpmr   Author: k8s-for-greeks   File: RaceResultResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #24
Source Project: pacbot   Author: tmobile   File: DatasourceControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
	MockitoAnnotations.initMocks(this);
	mockMvc = MockMvcBuilders.standaloneSetup(datasourceController)
			/* .addFilters(new CORSFilter()) */
			.build();
}
 
Example #25
Source Project: e-commerce-microservice   Author: xebialabs   File: WebConfigurerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #26
Source Project: e-commerce-microservice   Author: xebialabs   File: WebConfigurerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #27
Source Project: jhipster-microservices-example   Author: oktadeveloper   File: TagResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #28
Source Project: jhipster-online   Author: jhipster   File: YoRCResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #29
Source Project: OpenIoE   Author: scorelab   File: SensorResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #30
Source Project: cubeai   Author: cube-ai   File: WebConfigurerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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"));
}