单元测试覆盖调用 super() 的方法 [英] Unit testing overridden methods which call super()

查看:175
本文介绍了单元测试覆盖调用 super() 的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出为最后一步调用 super() 的重写方法编写单元测试的最佳方法.基本上,我想在基类中使用参数之前对其进行按摩.

I'm trying to figure out the best way of writing a unit test for an overridden method which calls super() as the last step. Basically, I want to massage parameters before they're used in the base class.

这是一个方法的例子:

    @Override
    public JobExecution run(Job job, JobParameters passedParams) 
            throws JobExecutionAlreadyRunningException, JobRestartException {

        JobParameters launchParameters;

        if(passedParams.isEmpty()) {
            launchParameters = jobParameterSetter.getJobParameters();
        } else {
            launchParameters = passedParams;
        }

        return super.run(job, launchParameters);
    }

归根结底是我找不到检查最终 super.run() 调用中的参数的接缝,这就是我想要测试的全部内容.基类有几个依赖项,真的没有必要测试那个类(更不用说更多的工作了).

What it comes down to is that I can't find a seam to check the parameters that are in the eventual super.run() call, which is all I want to test. The base class has several dependencies, and it's really not necessary to test that class (not to mention a lot more work).

Composition 是一种解决方案,但它是一个相当复杂的基类,我需要公开整个内容,同时只覆盖几个方法.

Composition is a solution, but it's a fairly complicated base class and I need to expose the whole thing while only overriding a couple of methods.

我也在考虑伪造用于测试的基类,这很简单,但我不确定如何更改类路径来运行单元测试(Eclipse 用于单个测试;Maven 用于构建测试——也许一个问题?).

I'm also considering faking the base class for testing, which is simple enough, but I'm not sure how to change the classpath just for running the unit test (Eclipse for single tests; Maven for build testing -- maybe a question on its own?).


我不得不想象这已经被问到了,但我找不到完全匹配的.


I have to imagine this has already been asked, but I can't find an exact match.

推荐答案

看来您要测试的逻辑是 if-else 流程,而不是对基类的调用.我将通过创建一个名为 getLaunchParameters(JobParameters jobParameters) 的受保护方法来实现这一点,该方法执行您有兴趣测试的一些逻辑.

It seems that the logic you are wanting to test is the if-else flow, and NOT the call to the base class. I would do this by creating a protected method called getLaunchParameters(JobParameters jobParameters), which does the bit of logic you are interested in testing.

通过这种方式,您要测试的逻辑得到了测试,您对测试不感兴趣的逻辑没有得到测试,并且您已经分解了一段代码,将来可能会在其他地方使用.

This way, the logic you want tested is tested, the logic you are not interested in testing is not tested, and you have broken out a piece of code that may be able to be used else where in the future.

这篇关于单元测试覆盖调用 super() 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆