参数化单元测试 - 不能同时使用@RunWith(SpringRunner.class) 和 @RunWith(Parameterized.class)

环境

SpringBoot:2.7.18,Junit:4.13.2

问题说明

Junit4 中,注入Spring上下文需要使用到@RunWith(SpringRunner.class),参数化测试需要使用到@RunWith(Parameterized.class),当单测的方法依赖Spring上下文,又想使用参数化测试时,只能使用一个@RunWith(),怎么办?

代码示例

  • Controller
@RestController
public class JunitController {

    @Autowired
    private JunitService junitService;

    @GetMapping("/n/{a}/{b}")
    public Integer getNumberType(@PathVariable Integer a, @PathVariable Integer b) {
        return junitService.determineNumberType(a, b);
    }
}
  • Service
@Service
public class JunitServiceImpl implements JunitService {

    // 两数相乘
    @Override
    public Integer determineNumberType(Integer a, Integer b) {
        return a * b;
    }
}
  • DAO

如果有数据库需求,同理,按需定义即可。


单测示例(已解决

依赖注入,按照代码中提示,补全 5 个步骤即可

@Slf4j
// 1、Junit 参数化测试
@RunWith(Parameterized.class)
// 需要使用 Spring 容器中的依赖, 注明这是一个测试类
@SpringBootTest
// 2、参数化测试时注入 Spring 上下文依赖需要这两个注解
@ContextConfiguration
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
public class JunitApiTest {

	// 3、申明测试上下文管理器
    private final TestContextManager testContextManager;

    @Autowired
    private JunitController junitController;

	// Service中需要使用到的参数,用于单测方法参数化测试
    private Integer n1;
    private Integer n2;

	// 4、在单测类的构造方法中传入参数,并定义测试上下文管理器
    public JunitApiTest(Integer n1, Integer n2) {
        this.testContextManager = new TestContextManager(getClass());
        this.n1 = n1;
        this.n2 = n2;
    }

	// 5、注入依赖项
    @Before
    public void injectDependencies() throws Throwable {
        this.testContextManager.prepareTestInstance(this);
    }

	// 参数化测试的参数
    @Parameterized.Parameters
    public static Collection<Object[]> prepareData() {
        return Arrays.asList(new Object[][]{
                {1, 1},
                {2, 2},
                {3, 3}
        });
    }

	// 单测方法中,调用传参直接传定义的参数名即可
    @Test
    public void judgeTest() {
        Integer result = junitController.getNumberType(n1, n2);
        log.info("输出结果:{}", result.toString());
    }

}

参考
https://blog.csdn.net/w605283073/article/details/80119030
https://blog.csdn.net/benweizhu/article/details/42365811
https://www.jianshu.com/p/029dee34da08
https://stackoverflow.com/questions/12798079/initializationerror-with-eclipse-and-junit4-when-executing-a-single-test/18438718

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值