前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot Junit4 参数化测试Controller

Spring Boot Junit4 参数化测试Controller

作者头像
明明如月学长
发布2021-08-27 16:20:06
9290
发布2021-08-27 16:20:06
举报
文章被收录于专栏:明明如月的技术专栏

由于Spring测试类上只能有一个@Runwith注解,如果使用@RunWith(Parameterized.class),就无法s使用@RunWith(SpringJUnit4ClassRunner.class)。

@RunWith(SpringJUnit4ClassRunner.class)是JUnit的注解,通过这个注解让SpringJUnit4ClassRunner 这个类提供Spring测试上下文 需要借助TestContextManager来实现上下文注入。

TestContextManager 与@RunWith(SpringJUnit4ClassRunner.class) 效果一样  

在spring-framework-reference中的介绍

可以参考如下文章,利用TestContextManager来注入 Spring

参考如下java Code Examples for org.springframework.test.context.TestContextManager.prepareTestInstance

示例如下:

代码语言:javascript
复制
package com.netease.ey.pay.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import javax.annotation.Resource;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@RunWith(Parameterized.class)
@SpringBootTest
@ContextConfiguration
@AutoConfigureMockMvc
public class PayControllerTest {
    private static final Logger logger = LoggerFactory.getLogger(PayControllerTest.class);

    @Resource
    private MockMvc mockMvc;

    private TestContextManager testContextManager;

    @Before
    public void setUp() throws Exception {
        testContextManager = new TestContextManager(getClass());
        testContextManager.prepareTestInstance(this);
    }


    @Parameterized.Parameters(name = "{index}:orderId:{0}")
    public static Object[] data() {
        return new Object[] { "1","7"};
    }
    @Parameterized.Parameter // first data value (0) is default
    public /* 不能为 private */ String orderId;

    @Test
    public void transfer() throws Exception {
        String response = mockMvc.perform(MockMvcRequestBuilders.post("/pay/transfer")
                .param("orderId", orderId))
                .andExpect(MockMvcResultMatchers.status().isOk()).andDo(print())         //打印出请求和相应的内容
                .andReturn().getResponse().getContentAsString();
        logger.info("返回值{}",response);

    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/04/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档