@Test
  public void testRegisterActivity() throws Exception {
    String userId = "412bac09-b9a0-46b5-a283-7442fa1eb76c";
    String token = "3f1d9898-5531-4753-80fa-2e164c5ba754";

    MvcResult result =
        mockMvc
            .perform(
                MockMvcRequestBuilders.post(
                        "/activity/register?userId=" + userId + "&token=" + token)
                    .param("type", "旅行")
                    .param("introduction", "DD活动期间晴空万里,道路通畅")
                    .param("cover", "4d51a321-f953-4623-b7ab-abd4fb858e77")
                    .param("cover", "59336875-0128-4121-862a-22d1db86fe03")
                    .param("location", "南京邮电大学")
                    .param("longitude", "118.869529")
                    .param("latitude", "32.02632")
                    .param("start", "1436494940937")
                    .param("end", "1436494955800")
                    .param("province", "江苏省")
                    .param("city", "南京")
                    .param("district", "鼓楼区")
                    .param("pay", "我请客")
                    .param("seat", "2"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().encoding("UTF-8"))
            .andExpect(
                MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.result").value(0))
            .andDo(MockMvcResultHandlers.print())
            .andReturn();
    Assert.assertNull(result.getModelAndView());
  }
 @Test
 public final void testUpdatePerson() throws Exception {
   Person person = createSamplePerson();
   Mockito.when(peopleServiceMock.updatePerson(Mockito.any(Person.class))).thenReturn(person);
   mockMvc
       .perform(
           MockMvcRequestBuilders.post("/person/update")
               .contentType(MediaType.APPLICATION_JSON)
               .content(JSONUtil.toJSonString(person).getBytes()))
       .andDo(MockMvcResultHandlers.print())
       .andExpect(MockMvcResultMatchers.status().isOk())
       .andExpect(MockMvcResultMatchers.content().string(JSONUtil.toJSonString(person)));
 }
  @Test
  public final void testAddFamily() throws Exception {
    Family family = createSampleFamily();
    Mockito.when(peopleServiceMock.addFamily(Mockito.any(Family.class))).thenReturn(family);

    mockMvc
        .perform(
            MockMvcRequestBuilders.post("/family")
                .contentType(MediaType.APPLICATION_JSON)
                .content(JSONUtil.toJSonString(family).getBytes()))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().string(JSONUtil.toJSonString(family)));
  }
  @Test
  public void shouldTriggerJobAndReturnItsURL() throws Exception {
    when(jobService.startAsyncJob("someJobType")).thenReturn(Optional.of("theJobId"));

    mockMvc
        .perform(
            MockMvcRequestBuilders.post("/some-microservice/internal/jobs/someJobType")
                .servletPath("/internal/jobs/someJobType"))
        .andExpect(MockMvcResultMatchers.status().is(204))
        .andExpect(
            MockMvcResultMatchers.header()
                .string("Location", "http://localhost/some-microservice/internal/jobs/theJobId"));

    verify(jobService).startAsyncJob("someJobType");
  }
  @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));
  }
 @Test
 public final void testAddFamilyWithFamilyExistsException() throws Exception {
   Family family = createSampleFamily();
   Mockito.doThrow(FamilyExistsException.class)
       .when(peopleServiceMock)
       .addFamily(Mockito.any(Family.class));
   mockMvc
       .perform(
           MockMvcRequestBuilders.post("/family")
               .contentType(MediaType.APPLICATION_JSON)
               .content(JSONUtil.toJSonString(family).getBytes()))
       .andDo(MockMvcResultHandlers.print())
       .andExpect(MockMvcResultMatchers.status().isBadRequest())
       .andExpect(
           MockMvcResultMatchers.jsonPath("['httpStatus']")
               .value(Matchers.containsString("BAD_REQUEST")));
 }
 @Test
 public void postAccountTest() throws Exception {
   mockMvc
       .perform(
           MockMvcRequestBuilders.post("/account")
               .contentType(MediaType.APPLICATION_FORM_URLENCODED)
               .param("name", accountForm.getName())
               .param("surname", accountForm.getSurname())
               .param("address", accountForm.getAddress())
               .param("phone", accountForm.getPhone().toString())
               .param("iban", accountForm.getIban().toString())
               .param("balance", accountForm.getBalance().toString())
               .param("currency", accountForm.getCurrency()))
       .andExpect(MockMvcResultMatchers.status().isOk())
       .andExpect(MockMvcResultMatchers.view().name("account"))
       .andExpect(MockMvcResultMatchers.model().attributeExists("currencies"))
       .andReturn();
 }
 @Test
 public void getAccountTest() throws Exception {
   mockMvc
       .perform(MockMvcRequestBuilders.get("/account"))
       .andExpect(MockMvcResultMatchers.status().isOk())
       .andExpect(MockMvcResultMatchers.view().name("account"))
       .andExpect(MockMvcResultMatchers.model().attributeExists("currencies"))
       .andReturn();
 }
  @Test
  public final void testDeletePerson() throws Exception {
    Mockito.doNothing().when(peopleServiceMock).deletePerson(Mockito.any(Long.class));

    mockMvc
        .perform(
            MockMvcRequestBuilders.delete("/delPerson/200").contentType(MediaType.APPLICATION_JSON))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().string(""));
  }
 @Test
 public void environmentWithLabelContainingSlash() throws Exception {
   Mockito.when(this.repository.findOne("foo", "default", "feature/puff"))
       .thenReturn(new Environment("foo", "default"));
   this.mvc
       .perform(MockMvcRequestBuilders.get("/foo/default/feature(_)puff"))
       .andExpect(MockMvcResultMatchers.status().isOk())
       .andExpect(
           MockMvcResultMatchers.content()
               .string(Matchers.containsString("\"propertySources\":")));
 }
 @Test
 public final void testGetFamily() throws Exception {
   Family family = createSampleFamily();
   Mockito.when(peopleServiceMock.getFamily(new Long(1))).thenReturn(family);
   mockMvc
       .perform(MockMvcRequestBuilders.get("/family/1").accept(MediaType.APPLICATION_JSON))
       .andDo(MockMvcResultHandlers.print())
       .andExpect(MockMvcResultMatchers.status().isOk())
       .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_VALUE))
       .andExpect(MockMvcResultMatchers.content().string(JSONUtil.toJSonString(family)));
 }
  @Test
  public void testShowRegisterForm() throws Exception {
    SpitterRepository spittleRepository = Mockito.mock(SpitterRepository.class);

    SpitterController spittlerController = new SpitterController(spittleRepository);
    MockMvc mockSpittleController = MockMvcBuilders.standaloneSetup(spittlerController).build();

    mockSpittleController
        .perform(MockMvcRequestBuilders.get("/spitter/register"))
        .andExpect(MockMvcResultMatchers.model().attributeExists("spitter"))
        .andExpect(MockMvcResultMatchers.view().name("registerForm"));
  }
  @Test
  public void testView() throws Exception {
    MvcResult result =
        mockMvc
            .perform(MockMvcRequestBuilders.get("/user/1"))
            .andExpect(MockMvcResultMatchers.view().name("user/view"))
            .andExpect(MockMvcResultMatchers.model().attributeExists("user"))
            .andDo(MockMvcResultHandlers.print())
            .andReturn();

    Assert.assertNotNull(result.getModelAndView().getModel().get("user"));
  }
  @Test
  public final void testFindPerson() throws Exception {
    Person person = createSamplePerson();
    List<Person> list = new ArrayList<Person>();
    list.add(person);

    Mockito.when(peopleServiceMock.findPerson("Andy")).thenReturn(list);
    mockMvc
        .perform(MockMvcRequestBuilders.get("/person/find/Andy").accept(MediaType.APPLICATION_JSON))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_VALUE))
        .andExpect(MockMvcResultMatchers.content().string(JSONUtil.toJSonString(list)));
  }
  @Test
  public final void testFindFamily() throws Exception {
    Family family = createSampleFamily();
    List<Family> list = new ArrayList<Family>();
    list.add(family);

    Mockito.when(peopleServiceMock.findFamily("Weber")).thenReturn(list);
    mockMvc
        .perform(
            MockMvcRequestBuilders.get("/family/find/Weber").accept(MediaType.APPLICATION_JSON))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_VALUE))
        .andExpect(MockMvcResultMatchers.content().string(JSONUtil.toJSonString(list)));
  }
Exemple #16
0
 @Test
 public void testMock() throws Exception {
   ResultActions resultActions = getResultActions(test);
   resultActions
       .andDo(MockMvcResultHandlers.print())
       .andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
 }
 @Test
 @Ignore
 public void verifiesHomePageLoads() throws Exception {
   mockMvc
       .perform(MockMvcRequestBuilders.get("/"))
       .andExpect(MockMvcResultMatchers.status().isOk());
 }
  @Test
  public void whenFlashAttributeIsPassedRepositoryIsNotCalled() throws Exception {
    SpitterRepository fakeSpitterRepository = Mockito.mock(SpitterRepository.class);
    Mockito.when(fakeSpitterRepository.findByUsername(Mockito.anyString()))
        .thenReturn(new Spitter());
    SpitterController spitterController = new SpitterController(fakeSpitterRepository);

    MockMvc mockSpitterController = MockMvcBuilders.standaloneSetup(spitterController).build();

    mockSpitterController
        .perform(MockMvcRequestBuilders.get("/spitter/gdiaz").flashAttr("spitter", new Spitter()))
        .andExpect(MockMvcResultMatchers.model().attributeExists("spitter"))
        .andExpect(MockMvcResultMatchers.view().name("profile"));

    Mockito.verify(fakeSpitterRepository, Mockito.never()).findByUsername(Mockito.anyString());
  }
 @Test
 public void T050Delete() throws Exception {
   mockMvc
       .perform(delete("/api/global/gitconfig/{id}", 3))
       .andDo(print())
       .andExpect(MockMvcResultMatchers.jsonPath("$.resultCode").value(ResultStat.OK.responseCode))
       .andExpect(status().isOk());
 }
 @Test
 public void environmentWithLabelContainingPeriod() throws Exception {
   Mockito.when(this.repository.findOne("foo", "default", "1.0.0"))
       .thenReturn(new Environment("foo", "default"));
   this.mvc
       .perform(MockMvcRequestBuilders.get("/foo/default/1.0.0"))
       .andExpect(MockMvcResultMatchers.status().isOk());
 }
 @Test
 public void propertiesLabelWithSlash() throws Exception {
   Mockito.when(this.repository.findOne("foo", "default", "label/spam"))
       .thenReturn(new Environment("foo", "default"));
   this.mvc
       .perform(MockMvcRequestBuilders.get("/label(_)spam/foo-default.properties"))
       .andExpect(MockMvcResultMatchers.status().isOk());
   Mockito.verify(this.repository).findOne("foo", "default", "label/spam");
 }
 @Test
 public void environmentNoLabel() throws Exception {
   Mockito.when(this.repository.findOne("foo", "default", null))
       .thenReturn(new Environment("foo", "default"));
   this.mvc
       .perform(MockMvcRequestBuilders.get("/foo/default"))
       .andExpect(MockMvcResultMatchers.status().isOk());
   Mockito.verify(this.repository).findOne("foo", "default", null);
 }
 @Test
 public void propertiesLabelWhenApplicationNameContainsHyphen() throws Exception {
   Mockito.when(this.repository.findOne("foo-bar", "default", "label"))
       .thenReturn(new Environment("foo-bar", "default"));
   this.mvc
       .perform(MockMvcRequestBuilders.get("/label/foo-bar-default.properties"))
       .andExpect(MockMvcResultMatchers.status().isOk());
   Mockito.verify(this.repository).findOne("foo-bar", "default", "label");
 }
  @Test
  public void testShowProfilePage() throws Exception {

    Spitter spitterUser = new Spitter(1L, "name", "secondname", "gdiaz", "");
    SpitterRepository spitterRepository = Mockito.mock(SpitterRepository.class);
    Mockito.when(spitterRepository.findByUsername(spitterUser.getUserName()))
        .thenReturn(spitterUser);
    SpitterController spitterController = new SpitterController(spitterRepository);

    MockMvc mockSpitterController = MockMvcBuilders.standaloneSetup(spitterController).build();

    mockSpitterController
        .perform(MockMvcRequestBuilders.get("/spitter/" + spitterUser.getUserName()))
        .andExpect(MockMvcResultMatchers.model().attributeExists("spitter"))
        .andExpect(MockMvcResultMatchers.view().name("profile"));

    Mockito.verify(spitterRepository, Mockito.atLeastOnce())
        .findByUsername(spitterUser.getUserName());
  }
  @Test
  public void shouldReturn404IfJobIsUnknown() throws Exception {
    // given
    when(jobService.findJob(any(String.class))).thenReturn(Optional.<JobInfo>empty());

    // when
    mockMvc
        .perform(MockMvcRequestBuilders.get("/some-microservice/internal/jobs/42"))
        .andExpect(MockMvcResultMatchers.status().is(404));
  }
 @Test
 public void testDefaults() throws Exception {
   tokenStore.storeAccessToken(token, authentication);
   AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
   context.setServletContext(new MockServletContext());
   context.register(ResourceServerContext.class);
   context.refresh();
   MockMvc mvc =
       MockMvcBuilders.webAppContextSetup(context)
           .addFilters(
               new DelegatingFilterProxy(
                   context.getBean("springSecurityFilterChain", Filter.class)))
           .build();
   mvc.perform(MockMvcRequestBuilders.get("/"))
       .andExpect(MockMvcResultMatchers.status().isUnauthorized());
   mvc.perform(MockMvcRequestBuilders.get("/").header("Authorization", "Bearer FOO"))
       .andExpect(MockMvcResultMatchers.status().isNotFound());
   context.close();
 }
 @Test
 public void T040Modify() throws Exception {
   mockMvc
       .perform(
           put("/api/global/gitconfig")
               .contentType(MediaType.APPLICATION_JSON)
               .content(gitConfigStr))
       .andDo(print())
       .andExpect(MockMvcResultMatchers.jsonPath("$.resultCode").value(ResultStat.OK.responseCode))
       .andExpect(status().isOk());
 }
  @Test
  public void jsonSyntaxErrorHandling() throws Exception {

    mockMvc
        .perform(
            post("/ni/notifyContext")
                .content("bad JSON")
                .contentType(MediaType.APPLICATION_JSON)
                .header("Host", "localhost")
                .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(
            MockMvcResultMatchers.jsonPath("$.responseCode.code")
                .value(CodeEnum.CODE_400.getLabel()))
        .andExpect(
            MockMvcResultMatchers.jsonPath("$.responseCode.reasonPhrase")
                .value(CodeEnum.CODE_400.getShortPhrase()))
        .andExpect(
            MockMvcResultMatchers.jsonPath("$.responseCode.details")
                .value(CodeEnum.CODE_400.getLongPhrase()));
  }
  @Test
  public void xmlSyntaxErrorHandling() throws Exception {

    mockMvc
        .perform(
            post("/ni/notifyContext")
                .content("bad xml")
                .contentType(MediaType.APPLICATION_XML)
                .header("Host", "localhost")
                .accept(MediaType.APPLICATION_XML))
        .andExpect(status().isOk())
        .andExpect(
            MockMvcResultMatchers.xpath("notifyContextResponse/responseCode/code")
                .string(CodeEnum.CODE_400.getLabel()))
        .andExpect(
            MockMvcResultMatchers.xpath("notifyContextResponse/responseCode/reasonPhrase")
                .string(CodeEnum.CODE_400.getShortPhrase()))
        .andExpect(
            MockMvcResultMatchers.xpath("notifyContextResponse/responseCode/details")
                .string(CodeEnum.CODE_400.getLongPhrase()));
  }
 @Test
 public void checkUpdateContextNotImplemented() throws Exception {
   mockMvc
       .perform(
           post("/ni/updateContext")
               .content(Util.json(jsonConverter, Util.createUpdateContextTempSensor(0)))
               .contentType(MediaType.APPLICATION_JSON)
               .header("Host", "localhost")
               .accept(MediaType.APPLICATION_JSON))
       .andExpect(status().isOk())
       .andExpect(
           MockMvcResultMatchers.jsonPath("$.errorCode.code").value(CodeEnum.CODE_403.getLabel()));
 }