Mock 测试web接口

BaseControllerTest

Mock 测试web接口

import com.google.common.collect.Lists;
import org.apache.rocketmq.dashboard.BaseTest;
import org.apache.rocketmq.dashboard.config.RMQConfigure;
import org.apache.rocketmq.dashboard.support.GlobalExceptionHandler;
import org.apache.rocketmq.dashboard.support.GlobalRestfulResponseBodyAdvice;
import org.apache.rocketmq.dashboard.util.MyPrintingResultHandler;
import org.apache.rocketmq.tools.admin.MQAdminExt;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public abstract class BaseControllerTest extends BaseTest {

    protected MockMvc mockMvc;

    @Mock
    protected MQAdminExt mqAdminExt;

    @Mock
    protected RMQConfigure configure;

    protected MockHttpServletRequestBuilder requestBuilder = null;

    protected ResultActions perform;

    protected abstract Object getTestController();

    @Before
    public void beforeInit() throws Exception {
        MockitoAnnotations.initMocks(this);
        autoInjection();
        createMockMvc();
    }

    protected void mockRmqConfigure() {
        when(configure.getAccessKey()).thenReturn("12345678");
        when(configure.getSecretKey()).thenReturn("rocketmq");
        when(configure.getNamesrvAddr()).thenReturn("127.0.0.1:9876");
        when(configure.getNamesrvAddrs()).thenReturn(Lists.newArrayList("127.0.0.1:9876", "127.0.0.2:9876"));
        when(configure.isACLEnabled()).thenReturn(true);
        when(configure.isUseTLS()).thenReturn(false);
    }

    protected ResultActions performOkExpect(ResultActions perform) throws Exception {
        return perform.andExpect(status().isOk())
            .andExpect(jsonPath("$").exists())
            .andExpect(jsonPath("$").isMap())
            .andExpect(jsonPath("$.data").exists())
            .andExpect(jsonPath("$.status").value(0))
            .andExpect(jsonPath("$.errMsg").doesNotExist());
    }

    protected ResultActions performErrorExpect(ResultActions perform) throws Exception {
        return perform.andExpect(status().isOk())
            .andExpect(jsonPath("$").exists())
            .andExpect(jsonPath("$.data").doesNotExist())
            .andExpect(jsonPath("$.status").value(-1))
            .andExpect(jsonPath("$.errMsg").isNotEmpty());
    }

    protected MockMvc createMockMvc() {
        MockMvc innerMockMvc = MockMvcBuilders.standaloneSetup(getTestController())
            .alwaysDo(MyPrintingResultHandler.me())
            .setControllerAdvice(new GlobalExceptionHandler(), new GlobalRestfulResponseBodyAdvice())
            .build();
        this.mockMvc = innerMockMvc;
        return innerMockMvc;
    }

}

测试web接口 单元测试模拟


 @Test
    public void testTopic() throws Exception {
        final String url = "/dashboard/topic.query";
        // 1、topicName is empty
        // 1.1、no topic cache data
        requestBuilder = MockMvcRequestBuilders.get(url);
        requestBuilder.param("date", yesterdayDateStr);
        perform = mockMvc.perform(requestBuilder);
        perform.andExpect(status().isOk())
            .andExpect(jsonPath("$.data").isMap())
            .andExpect(jsonPath("$.data").isEmpty());

        // 1.2、the topic's data is cached locally
        requestBuilder = MockMvcRequestBuilders.get(url);
        requestBuilder.param("date", nowDateStr);
        perform = mockMvc.perform(requestBuilder);
        perform.andExpect(status().isOk())
            .andExpect(jsonPath("$.data").isMap())
            .andExpect(jsonPath("$.data").isNotEmpty())
            .andExpect(jsonPath("$.data", hasKey("topic_test")))
            .andExpect(jsonPath("$.data.topic_test").isArray())
            .andExpect(jsonPath("$.data.topic_test", hasSize(100)));

        // 2、topicName is not empty
        requestBuilder = MockMvcRequestBuilders.get(url);
        requestBuilder.param("date", nowDateStr);
        requestBuilder.param("topicName", "topic_test");
        perform = mockMvc.perform(requestBuilder);
        perform.andExpect(status().isOk())
            .andExpect(jsonPath("$.data").isArray())
            .andExpect(jsonPath("$.data", hasSize(100)));

        // 2、topicName is not empty but the no topic cache data
        requestBuilder = MockMvcRequestBuilders.get(url);
        requestBuilder.param("date", nowDateStr);
        requestBuilder.param("topicName", "topic_test1");
        perform = mockMvc.perform(requestBuilder);
        perform.andExpect(status().isOk());

    }
    
@Test
public void testQueryMessagePageByTopic() throws Exception {
    final String url = "/message/queryMessagePageByTopic.query";
    MessageQuery query = new MessageQuery();
    query.setPageNum(1);
    query.setPageSize(10);
    query.setTopic("topic_test");
    query.setTaskId("");
    query.setBegin(System.currentTimeMillis() - 3 * 24 * 60 * 60 * 1000);
    query.setEnd(System.currentTimeMillis());

    // missed cache
    requestBuilder = MockMvcRequestBuilders.post(url);
    requestBuilder.contentType(MediaType.APPLICATION_JSON_UTF8);
    requestBuilder.content(JSON.toJSONString(query));
    perform = mockMvc.perform(requestBuilder);
    perform.andExpect(status().isOk())
        .andExpect(jsonPath("$.data.page.content", hasSize(1)))
        .andExpect(jsonPath("$.data.page.content[0].msgId").value("0A9A003F00002A9F0000000000000319"));

    String taskId = MessageClientIDSetter.createUniqID();
    {
        List<QueueOffsetInfo> queueOffsetInfos = new ArrayList<>();
        int idx = 0;
        for (MessageQueue messageQueue : messageQueues) {
            Long minOffset = defaultMQPullConsumer.searchOffset(messageQueue, query.getBegin());
            Long maxOffset = defaultMQPullConsumer.searchOffset(messageQueue, query.getEnd()) + 1;
            queueOffsetInfos.add(new QueueOffsetInfo(idx++, minOffset, maxOffset, minOffset, minOffset, messageQueue));
        }
        // Use reflection to add data to the CACHE
        Field field = MessageServiceImpl.class.getDeclaredField("CACHE");
        field.setAccessible(true);
        Cache<String, List<QueueOffsetInfo>> cache = (Cache<String, List<QueueOffsetInfo>>) field.get(messageService);
        cache.put(taskId, queueOffsetInfos);
    }

    // hit cache
    query.setTaskId(taskId);
    requestBuilder.content(JSON.toJSONString(query));
    perform = mockMvc.perform(requestBuilder);
    perform.andExpect(status().isOk())
        .andExpect(jsonPath("$.data.page.content", hasSize(1)))
        .andExpect(jsonPath("$.data.page.content[0].msgId").value("0A9A003F00002A9F0000000000000319"));
}

@Test
public void testQueryMessageByTopic() throws Exception {
    final String url = "/message/queryMessageByTopic.query";
    requestBuilder = MockMvcRequestBuilders.get(url);
    requestBuilder.param("topic", "topic_test")
        .param("begin", Long.toString(System.currentTimeMillis() - 3 * 24 * 60 * 60 * 1000))
        .param("end", Long.toString(System.currentTimeMillis()));
    perform = mockMvc.perform(requestBuilder);
    perform.andExpect(status().isOk())
        .andExpect(jsonPath("$.data", hasSize(1)))
        .andExpect(jsonPath("$.data[0].msgId").value("0A9A003F00002A9F0000000000000319"));
}

你可能感兴趣的:(项目开发SSM,boot要点,前端,servlet,java,单元测试,mock)