@Test public void shouldProcessRegistration() throws Exception { Spitter unsaved = new Spitter("Gustavo", "Diaz", "gdiaz", "gd123"); Spitter saved = new Spitter(24L, "Gustavo", "Diaz", "gdiaz", "gd123"); SpitterRepository spittlerRepository = Mockito.mock(SpitterRepository.class); Mockito.when(spittlerRepository.save(unsaved)).thenReturn(saved); SpitterController spittleController = new SpitterController(spittlerRepository); MockMvc mockSpittleController = MockMvcBuilders.standaloneSetup(spittleController).build(); mockSpittleController .perform( MockMvcRequestBuilders.post("/spitter/registerNoPic") .param("firstName", "Gustavo") .param("lastName", "Diaz") .param("userName", "gdiaz") .param("password", "gd123")) .andExpect( MockMvcResultMatchers.redirectedUrl( "/spitter/" + unsaved.getUserName() + "?id=" + unsaved.getFirstName())); // capture arguments pass to save call. ArgumentCaptor<Spitter> spitterArgumentCaptor = ArgumentCaptor.forClass(Spitter.class); Mockito.verify(spittlerRepository, Mockito.atLeastOnce()).save(spitterArgumentCaptor.capture()); // assert save method was called using same arguments. Assert.assertThat( spitterArgumentCaptor.getValue(), org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs(unsaved)); }
@Before public void setup() { TagController tagController = new TagController(); ReflectionTestUtils.setField(tagController, "timelineService", timelineService); ReflectionTestUtils.setField(tagController, "tagMembershipService", tagMembershipService); ReflectionTestUtils.setField(tagController, "userTagRepository", userTagRepository); User authenticateUser = constructAUser(username + "@ippon.fr"); AuthenticationService mockAuthenticationService = mock(AuthenticationService.class); when(mockAuthenticationService.getCurrentUser()).thenReturn(authenticateUser); ReflectionTestUtils.setField(tagController, "authenticationService", mockAuthenticationService); ReflectionTestUtils.setField( timelineService, "authenticationService", mockAuthenticationService); ReflectionTestUtils.setField( statusUpdateService, "authenticationService", mockAuthenticationService); ReflectionTestUtils.setField( tagMembershipService, "authenticationService", mockAuthenticationService); this.mockMvc = MockMvcBuilders.standaloneSetup(tagController).build(); TimelineController timelineController = new TimelineController(); ReflectionTestUtils.setField(timelineController, "timelineService", timelineService); ReflectionTestUtils.setField(timelineController, "statusUpdateService", statusUpdateService); this.timelineMockMvc = MockMvcBuilders.standaloneSetup(timelineController).build(); }
@Before public void setup() { Mockito.reset(bookService); InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/templates/"); viewResolver.setSuffix(".html"); mockMvc = MockMvcBuilders.standaloneSetup(new BookController()) .setViewResolvers(viewResolver) .build(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); }
@Test public void mock_mvc_instance_is_overwritten_when_defined_in_specification() { // Given MockMvc otherMockMvcInstance = MockMvcBuilders.standaloneSetup(new PostController()).build(); MockMvc thisMockMvcInstance = MockMvcBuilders.standaloneSetup(new GreetingController()).build(); MockMvcRequestSpecification specToMerge = new MockMvcRequestSpecBuilder().setMockMvc(otherMockMvcInstance).build(); // When MockMvcRequestSpecification spec = given().mockMvc(thisMockMvcInstance).spec(specToMerge); // Then assertThat(implOf(spec).getInstanceMockMvc()).isSameAs(otherMockMvcInstance); }
@BeforeClass(alwaysRun = true) public void init() throws Exception { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build(); testUser = new SpringUser( 3L, "*****@*****.**", "Test", "User", "testuser", "testuser", "es", getGrantedAuthorities(), true, true, true, true); token = new TokenHandler( DatatypeConverter.parseBase64Binary( "9SyECk96oDsTmXfogIfgdjhdsgvagHJLKNLvfdsfR8cbXTvoPjX+Pq/T/b1PqpHX0lYm0oCBjXWICA==")) .createTokenForUser(testUser); }
@Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(petController) .setConversionService(formattingConversionServiceFactoryBean.getObject()) .build(); }
@Test @Transactional public void getBloodPressureForLast30Days() throws Exception { ZonedDateTime now = ZonedDateTime.now(); ZonedDateTime firstOfMonth = now.withDayOfMonth(1); ZonedDateTime firstDayOfLastMonth = firstOfMonth.minusMonths(1); createBloodPressureByMonth(firstOfMonth, firstDayOfLastMonth); // create security-aware mockMvc restBloodPressureMockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); // Get all the blood pressure readings restBloodPressureMockMvc .perform(get("/api/bloodPressures").with(user("user").roles("USER"))) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$", hasSize(6))); // Get the blood pressure readings for the last 30 days restBloodPressureMockMvc .perform(get("/api/bp-by-days/{days}", 30).with(user("user").roles("USER"))) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.period").value("Last 30 Days")) .andExpect(jsonPath("$.readings.[*].systolic").value(hasItem(120))) .andExpect(jsonPath("$.readings.[*].diastolic").value(hasItem(75))); }
@Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) .addFilter(springSecurityFilterChain) .build(); }
@Before public void setup() { logger.info("setup"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); User user = null; try { user = userService.findByLogin("johndoe"); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } Authentication authentication = null; if (user != null) { authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword()); } Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(result); session = new MockHttpSession(); session.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); }
@Test public void correctlyRecordsMetricsForFailedDeferredResultResponse() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, MetricFilterAutoConfiguration.class); MetricsFilter filter = context.getBean(MetricsFilter.class); CountDownLatch latch = new CountDownLatch(1); MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController(latch)) .addFilter(filter) .build(); String attributeName = MetricsFilter.class.getName() + ".StopWatch"; MvcResult result = mvc.perform(post("/createFailure")) .andExpect(status().isOk()) .andExpect(request().asyncStarted()) .andExpect(request().attribute(attributeName, is(notNullValue()))) .andReturn(); latch.countDown(); try { mvc.perform(asyncDispatch(result)); fail(); } catch (Exception ex) { assertThat(result.getRequest().getAttribute(attributeName)).isNull(); verify(context.getBean(CounterService.class)).increment("status.500.createFailure"); } finally { context.close(); } }
@PostConstruct public void setup() { MockitoAnnotations.initMocks(this); CouponResource couponResource = new CouponResource(); ReflectionTestUtils.setField(couponResource, "couponRepository", couponRepository); this.restCouponMockMvc = MockMvcBuilders.standaloneSetup(couponResource).build(); }
@Test public void testUpdatePasswordBadCurrentPassword() throws Exception { String username = "******"; String currentPassword = "******"; String password = "******"; mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); // user must ge logged in HttpSession session = mockMvc .perform( post("/j_security_check").param("j_username", "admin").param("j_password", "admin")) .andExpect(status().is(HttpStatus.FOUND.value())) .andExpect(redirectedUrl("/")) .andReturn() .getRequest() .getSession(); mockMvc .perform( post("/updatePassword") .session((MockHttpSession) session) .param("username", username) .param("currentPassword", currentPassword) .param("password", password)) .andExpect(status().isOk()); assertNull(session.getAttribute(BaseFormController.MESSAGES_KEY)); assertNotNull(session.getAttribute(BaseFormController.ERRORS_MESSAGES_KEY)); }
@Before public void setup() { UserResource userResource = new UserResource(); ReflectionTestUtils.setField(userResource, "userRepository", userRepository); ReflectionTestUtils.setField(userResource, "userService", userService); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource).build(); }
@Test public void testGetText() throws Exception { String inputString = "User related info!"; FormData data = new FormData(); data.setComment(inputString); mockMvc = MockMvcBuilders.standaloneSetup(new ActionController()).build(); MvcResult result = this.mockMvc .perform(get("/users").contentType(MediaType.APPLICATION_JSON).content(data.toString())) .andExpect(status().isOk()) .andReturn(); String returnString = result.getResponse().getContentAsString(); ObjectMapper objectMapper = new ObjectMapper(); logger.info("Call to /users returned: " + returnString); // convert json string to object FormActionResult returnData = objectMapper.readValue(returnString.getBytes(), FormActionResult.class); String expectedString = returnData.getFormData().getComment(); logger.debug("USERS ACTION RETURNED: " + expectedString); assertTrue( "Expected data: \"" + inputString + "\" actual data=\"" + expectedString + "\" ", inputString.equals(expectedString)); }
@Before public void setup() { MockitoAnnotations.initMocks(this); account = new Account( "john", "malkovich", "Ireland", new BigInteger("500600700"), new BigInteger("1234567890"), new BigDecimal(25), "EUR"); accountForm = new AccountForm(); accountForm.setName("john"); accountForm.setSurname("malkovich"); accountForm.setAddress("Ireland"); accountForm.setPhone(new BigInteger("500600700")); accountForm.setIban(new BigInteger("1234567890")); accountForm.setBalance(new BigDecimal(25)); accountForm.setCurrency("EUR"); viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); mockMvc = MockMvcBuilders.standaloneSetup(accountController).setViewResolvers(viewResolver).build(); }
@PostConstruct public void setup() { MockitoAnnotations.initMocks(this); TableNoResource tableNoResource = new TableNoResource(); ReflectionTestUtils.setField(tableNoResource, "tableNoRepository", tableNoRepository); this.restTableNoMockMvc = MockMvcBuilders.standaloneSetup(tableNoResource).build(); }
@BeforeMethod public void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(homeController) .setMessageConverters(new GsonHttpMessageConverter()) .build(); }
@PostConstruct public void setup() { MockitoAnnotations.initMocks(this); DTUserResource dTUserResource = new DTUserResource(); ReflectionTestUtils.setField(dTUserResource, "dTUserRepository", dTUserRepository); this.restDTUserMockMvc = MockMvcBuilders.standaloneSetup(dTUserResource).build(); }
@PostConstruct public void setup() { MockitoAnnotations.initMocks(this); AuthorResource authorResource = new AuthorResource(); ReflectionTestUtils.setField(authorResource, "authorRepository", authorRepository); this.restAuthorMockMvc = MockMvcBuilders.standaloneSetup(authorResource).build(); }
@Before public void setUp() throws Exception { this.mock = MockMvcBuilders.webAppContextSetup(wac).build(); test = new ResultMessage(); test.set_result("success"); test.set_resultCode("200"); }
@Before @Transactional public void setUp() throws Exception { comment = repo.save(new Comment(ObjectId.get().toHexString(), 1L, "#foos")); this.parser = new JsonParser(mapper); mvc = MockMvcBuilders.webAppContextSetup(wac).alwaysDo(print()).build(); }
@Before public void setup() { MockitoAnnotations.initMocks(this); AuditEventService auditEventService = new AuditEventService(auditEventRepository, auditEventConverter); AuditResource auditResource = new AuditResource(auditEventService); this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource).build(); }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mvc = MockMvcBuilders.standaloneSetup(logController).build(); setUpActivityServiceMock(); setUpLogServiceMock(); }
@Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration()) .alwaysDo(document("{method-name}/{step}/")) .build(); }
@Before public void setUp() { Mockito.reset(userServiceMock); mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); SecurityContextHolder.getContext().setAuthentication(null); }
@Before public void init() { MockitoAnnotations.initMocks(this); tc = new MobileController(); ReflectionTestUtils.setField(tc, "tripsService", tripsService); ReflectionTestUtils.setField(tc, "messageSource", messageSource); mockMvc = MockMvcBuilders.standaloneSetup(tc).build(); }
@Before public void setUp() throws java.text.ParseException { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); user.setName("User Name"); user.setEmail("*****@*****.**"); user.setPicture( "https://lh4.googleusercontent.com/-N5NiXjGy98Q/AAAAAAAAAAI/AAAAAAAAAB4/GhIWSa3iyR4/photo.jpg"); }
@Before public void setUp() throws Exception { // this.mockMvc = // MockMvcBuilders.webAppContextSetup(this.wac).addFilter(this.springSecurityFilterChain).build(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); mockMvc.perform(post("/api/user/login").param("username", "admin").param("password", "admin")); }
@Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); TestUtility.initialize(); TestUtility.setUp(userDao, profileDao); this.authUser = TestUtility.createPrincipal(TestUtility.testUser.getEmail(), "password", "ROLE_TUTOR"); }
@Before public void setUp() { logger.debug("LocalSystemTest::setUp"); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) .addFilter(transactionFilter) .build(); }