io.curly.advisor.web.ReviewResourceControllerTests.java Source code

Java tutorial

Introduction

Here is the source code for io.curly.advisor.web.ReviewResourceControllerTests.java

Source

/*
 *        Copyright 2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package io.curly.advisor.web;

import io.curly.advisor.AdvisorApplication;
import io.curly.advisor.model.Review;
import io.curly.advisor.model.ReviewEntity;
import io.curly.advisor.model.UserInfo;
import io.curly.advisor.repository.ReviewCacheAwareService;
import io.curly.commons.github.User;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author Joao Pedro Evangelista
 */
@DirtiesContext
@RunWith(SpringJUnit4ClassRunner.class)
@OAuth2ContextConfiguration
@SpringApplicationConfiguration(classes = { AdvisorApplication.class })
@WebIntegrationTest
public class ReviewResourceControllerTests {

    private MockMvc mockMvc;

    private String artifact;

    private Review review;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private ReviewCacheAwareService reviewCacheAwareService;
    private ReviewEntity reviewEntity;

    @Before
    public void setUp() throws Exception {
        reviewCacheAwareService.getRepository().deleteAll();
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).alwaysDo(print()).build();
        this.artifact = ObjectId.get().toHexString();
        createReview();
        this.review = reviewCacheAwareService.save(new Review("so much content", artifact, "6969", "Cool!",
                new UserInfo("joao", "http://somevalidurl.com/photo.png"), new BigDecimal("4.5")));
    }

    private void createReview() {
        this.reviewEntity = new ReviewEntity();
        reviewEntity.setArtifact(ObjectId.get().toHexString());
        reviewEntity.setContent("abcd");
        reviewEntity.setTitle("some fancy title");
        reviewEntity.setRate(BigDecimal.ONE);
    }

    @After
    public void tearDown() throws Exception {
        reviewCacheAwareService.getRepository().deleteAll();
    }

    @Test
    public void testGetAllByArtifact() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.asyncDispatch(
                mockMvc.perform(get("/reviews/artifact/{artifact}", artifact)).andExpect(request().asyncStarted())
                        .andExpect(request().asyncResult(instanceOf(ResponseEntity.class))).andReturn()));
    }

    @Test
    public void testSave() throws Exception {
        System.out.println(reviewEntity);
        System.out.println(entity(reviewEntity));
        mockMvc.perform(post("/reviews").content(entity(reviewEntity)).contentType(MediaType.APPLICATION_JSON)
                .principal(User.builder().name("Joao").avatarUrl("example.com").id("6969").build()))
                .andExpect(status().isCreated());
        TimeUnit.MILLISECONDS.sleep(5000);
        List<Review> reviews = reviewCacheAwareService.getRepository()
                .findAllByOwner("6969", new PageRequest(0, 20)).getContent();

        Assert.assertThat(reviews, hasSize(2));
        Assert.assertThat(reviews.get(1).getRate(), is(BigDecimal.ONE));
    }

    @Test
    public void testGetAllByOwner() throws Exception {
        mockMvc.perform(
                asyncDispatch(mockMvc.perform(get("/reviews/owned").principal(User.builder().id("6969").build()))
                        .andExpect(request().asyncStarted())
                        .andExpect(request().asyncResult(instanceOf(ResponseEntity.class))).andReturn()));

    }

    private String entity(ReviewEntity reviewEntity) {
        MockHttpOutputMessage message = new MockHttpOutputMessage();
        try {
            new MappingJackson2HttpMessageConverter().write(reviewEntity, MediaType.APPLICATION_JSON, message);
        } catch (IOException ignore) {
        }
        return message.getBodyAsString();
    }
}