美文网首页
单元测试

单元测试

作者: 曹赫洋 | 来源:发表于2020-01-03 12:04 被阅读0次

    DataControllerTest.java

    package com.caoheyang;
    
    import com.caoheyang.controller.DataController;
    import com.caoheyang.model.request.GenerateShortUrlDomain;
    import com.caoheyang.model.response.ShortUrlDomain;
    import com.caoheyang.service.ShortUrlService;
    import com.google.gson.Gson;
    import net.minidev.json.JSONUtil;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.util.ReflectionTestUtils;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    import java.net.URI;
    
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    /**
     * DataController单元测试
     *
     * @author CaoHeYang
     * @date 2019/12/29
     */
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    public class DataControllerTest {
    
        @Autowired
        private DataController dataController;
    
        @Mock
        private ShortUrlService shortUrlService;
    
        @Autowired
        private WebApplicationContext context;
        private MockMvc mockMvc;
    
        @Before
        public void before() {
            ReflectionTestUtils.setField(dataController, "shortUrlService", shortUrlService);
            mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
        }
    
        @Test
        public void generateShortUrlTest() throws Exception {
            GenerateShortUrlDomain shortUrlDomain = new GenerateShortUrlDomain();
            shortUrlDomain.setLongUrl("https://www.baidu.com");
            Mockito.when(shortUrlService.generateShortUrl(shortUrlDomain)).thenReturn("jeMZfm");
            Gson gson = new Gson();
            mockMvc.perform(post(new URI("/data/shorten"))
                    .content(gson.toJson(shortUrlDomain))
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(status().isOk()).andReturn();
        }
    }
    

    HomeControllerTest.java

    package com.caoheyang;
    
    import com.caoheyang.controller.HomeController;
    import com.caoheyang.service.ShortUrlService;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.util.ReflectionTestUtils;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    /**
     * HomeController单元测试
     *
     * @author CaoHeYang
     * @date 2019/12/29
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    public class HomeControllerTest {
    
        @Autowired
        private HomeController homeController;
    
        @Mock
        private ShortUrlService shortUrlService;
    
        @Autowired
        private WebApplicationContext context;
        private MockMvc mockMvc;
    
        @Before
        public void before() {
            ReflectionTestUtils.setField(homeController, "shortUrlService", shortUrlService);
            mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
        }
    
        @Test
        public void redirectTest() throws Exception {
            Mockito.when(shortUrlService.getRedirectUrl("jeMZfm")).thenReturn("https://www.baidu.com");
            mockMvc.perform(get("/jeMZfm"))
                    .andExpect(status()
                            .is(302)).andReturn();
        }
    }
    

    ShortUrlServiceTest.java

    package com.caoheyang;
    
    import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
    import com.caoheyang.model.dynamo.TinyUrlItem;
    import com.caoheyang.model.request.GenerateShortUrlDomain;
    import com.caoheyang.service.ShortUrlService;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.util.ReflectionTestUtils;
    
    /**
     * ShortUrlService单元测试
     *
     * @author CaoHeYang
     * @date 2019/12/29
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    public class ShortUrlServiceTest {
    
        @Mock
        private DynamoDBMapper mapper;
    
        @Autowired
        private ShortUrlService shortUrlService;
    
    
        @Before
        public void before() throws Exception {
            ReflectionTestUtils.setField(shortUrlService, "mapper", mapper);
        }
    
        @Test
        public void generateShortUrlTest() {
            TinyUrlItem tinyUrlItem = new TinyUrlItem();
            tinyUrlItem.setLongUrl("https://www.baidu.com");
            Mockito.doNothing().when(mapper).save(tinyUrlItem);
            GenerateShortUrlDomain domain = new GenerateShortUrlDomain();
            String url = shortUrlService.generateShortUrl(domain);
            System.out.println(url);
        }
    
    
        @Test
        public void getRedirectUrlTest() {
            TinyUrlItem tinyUrlItem = new TinyUrlItem();
            tinyUrlItem.setLongUrl("https://www.baidu.com");
            Mockito.when(mapper.load(TinyUrlItem.class, "jeMZfm")).thenReturn(tinyUrlItem);
            String str = shortUrlService.getRedirectUrl("jeMZfm");
            System.out.println(str);
        }
    
        @Test
        public void getRedirectUrlTestIsNull() {
            Mockito.when(mapper.load(TinyUrlItem.class, "jeMZfm")).thenReturn(null);
            String str = shortUrlService.getRedirectUrl("jeMZfm");
            System.out.println(str);
        }
    }
    

    StreamLambdaHandlerTest.java

    package com.caoheyang;
    
    import com.amazonaws.serverless.proxy.internal.LambdaContainerHandler;
    import com.amazonaws.serverless.proxy.internal.testutils.AwsProxyRequestBuilder;
    import com.amazonaws.serverless.proxy.internal.testutils.MockLambdaContext;
    import com.amazonaws.serverless.proxy.model.AwsProxyResponse;
    import com.amazonaws.services.lambda.runtime.Context;
    
    import com.caoheyang.serverless.StreamLambdaHandler;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    import javax.ws.rs.HttpMethod;
    import javax.ws.rs.core.HttpHeaders;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import static org.junit.Assert.*;
    
    /**
     * AWS Proxy Lambda
     *
     * @author CaoHeYang
     * @date 20191221
     */
    public class StreamLambdaHandlerTest {
    
        private static StreamLambdaHandler handler;
        private static Context lambdaContext;
    
        @BeforeClass
        public static void setUp() {
            handler = new StreamLambdaHandler();
            lambdaContext = new MockLambdaContext();
        }
    
        @Test
        public void ping_streamRequest_respondsWithHello() {
            InputStream requestStream = new AwsProxyRequestBuilder("/jeMZfm", HttpMethod.GET)
                                                .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
                                                .buildStream();
            ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
    
            handle(requestStream, responseStream);
    
            AwsProxyResponse response = readResponse(responseStream);
        }
    
        @Test
        public void invalidResource_streamRequest_responds404() {
            InputStream requestStream = new AwsProxyRequestBuilder("/short/jeMZfm", HttpMethod.GET)
                                                .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
                                                .buildStream();
            ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
    
            handle(requestStream, responseStream);
    
            AwsProxyResponse response = readResponse(responseStream);
            assertNotNull(response);
            assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode());
        }
    
        private void handle(InputStream is, ByteArrayOutputStream os) {
            try {
                handler.handleRequest(is, os, lambdaContext);
            } catch (IOException e) {
                e.printStackTrace();
                fail(e.getMessage());
            }
        }
    
        private AwsProxyResponse readResponse(ByteArrayOutputStream responseStream) {
            try {
                return LambdaContainerHandler.getObjectMapper().readValue(responseStream.toByteArray(), AwsProxyResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
                fail("Error while parsing response: " + e.getMessage());
            }
            return null;
        }
    }

    相关文章

      网友评论

          本文标题:单元测试

          本文链接:https://www.haomeiwen.com/subject/dqjzoctx.html