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 File: CredentialsTypeSpecificGenerateIntegrationTest.java    From credhub with 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 #2
Source File: PointsResourceIntTest.java    From 21-points with 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 File: PreferencesResourceIntTest.java    From 21-points with 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 #4
Source File: CustomerControllerTest.java    From market with 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 File: OrdersControllerTest.java    From market with 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 File: WebConfigurerTest.java    From e-commerce-microservice with 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 #7
Source File: WebConfigurerTest.java    From 21-points with 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 #8
Source File: TestChronosController.java    From chronos with 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 #9
Source File: PostResourceIT.java    From java-microservices-examples with 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 #10
Source File: MockMvcWebClientBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-14066
public void cookieManagerShared() throws Exception {
	this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build();
	WebClient client = MockMvcWebClientBuilder.mockMvcSetup(this.mockMvc).build();

	assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("NA"));
	client.getCookieManager().addCookie(new Cookie("localhost", "cookie", "cookieManagerShared"));
	assertThat(getResponse(client, "http://localhost/").getContentAsString(), equalTo("cookieManagerShared"));
}
 
Example #11
Source File: ContractBaseTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {

  RestAssuredMockMvc
    .mockMvc(
      MockMvcBuilders
        .webAppContextSetup(webApplicationContext)
        .apply(springSecurity())
        .build()
    );
}
 
Example #12
Source File: PostResourceIntTest.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    final PostResource postResource = new PostResource(postRepository, mockPostSearchRepository);
    this.restPostMockMvc = MockMvcBuilders.standaloneSetup(postResource)
        .setCustomArgumentResolvers(pageableArgumentResolver)
        .setControllerAdvice(exceptionTranslator)
        .setConversionService(createFormattingConversionService())
        .setMessageConverters(jacksonMessageConverter).build();
}
 
Example #13
Source File: WebConfigurerTest.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
@Test
public void testCorsFilterDeactivated() throws Exception {
    props.getCors().setAllowedOrigins(null);

    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 #14
Source File: WebConfigurerTest.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Test
public void testCorsFilterDeactivated() throws Exception {
    props.getCors().setAllowedOrigins(null);

    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 #15
Source File: EntityManagerControllerTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(controller)
            .addInterceptors(entandoOauth2Interceptor)
            .setHandlerExceptionResolvers(createHandlerExceptionResolver())
            .build();
    entityManagerService.setEntityManagers(new ArrayList<>());
}
 
Example #16
Source File: PointsResourceIntTest.java    From 21-points with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    final PointsResource pointsResource = new PointsResource(pointsRepository, mockPointsSearchRepository, userRepository);
    this.restPointsMockMvc = MockMvcBuilders.standaloneSetup(pointsResource)
        .setCustomArgumentResolvers(pageableArgumentResolver)
        .setControllerAdvice(exceptionTranslator)
        .setConversionService(createFormattingConversionService())
        .setMessageConverters(jacksonMessageConverter).build();
}
 
Example #17
Source File: MvcIntegrationTests.java    From kaif with Apache License 2.0 5 votes vote down vote up
@Before
public final void setUpMvc() {
  mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  Mockito.reset(accountService,
      zoneService,
      articleService,
      voteService,
      feedService,
      honorRollService,
      clientAppService);
}
 
Example #18
Source File: RaceResultResourceIntTest.java    From gpmr with 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 #19
Source File: ExceptionTranslatorIntTest.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(controller)
        .setControllerAdvice(exceptionTranslator)
        .setMessageConverters(jacksonMessageConverter)
        .build();
}
 
Example #20
Source File: GetPermissionsV2EndToEndTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeEach() throws Exception {
  mockMvc = MockMvcBuilders
    .webAppContextSetup(webApplicationContext)
    .apply(springSecurity())
    .build();
}
 
Example #21
Source File: WebConfigurerTest.java    From jhipster-microservices-example with 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 #22
Source File: BrokerApiVersionInterceptorIntegrationTest.java    From spring-boot-cf-service-broker with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	MockitoAnnotations.initMocks(this);

    this.mockMvc = MockMvcBuilders.standaloneSetup(controller)
    		.addInterceptors(new BrokerApiVersionInterceptor(new BrokerApiVersion("header","version")))
            .setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
}
 
Example #23
Source File: StyleControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
void before() {
  initMocks(this);
  StyleController styleController = new StyleController(styleService);

  mockMvc = MockMvcBuilders.standaloneSetup(styleController).build();
}
 
Example #24
Source File: WebConfigurerTest.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
@Test
public void testCorsFilterDeactivated() throws Exception {
    props.getCors().setAllowedOrigins(null);

    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 #25
Source File: WebConfigurerTest.java    From cubeai with 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"));
}
 
Example #26
Source File: SensorResourceIntTest.java    From OpenIoE with 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 #27
Source File: YoRCResourceIntTest.java    From jhipster-online with 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 #28
Source File: TagResourceIntTest.java    From jhipster-microservices-example with 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 #29
Source File: WebConfigurerTest.java    From e-commerce-microservice with 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 #30
Source File: WebConfigurerTest.java    From e-commerce-microservice with 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));
}