使用JUnit 4的预期异常机制导致意外行为的原因? [英] Cause of an unexpected behaviour using JUnit 4's expected exception mechanism?

查看:78
本文介绍了使用JUnit 4的预期异常机制导致意外行为的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试特定方法是否从该方法引发了预期的异常.根据JUnit4文档和此答案我将测试写为:

I am trying to test that a particular method throws an expected exception from a method. As per JUnit4 documentation and this answer I wrote the test as:

@Test(expected=CannotUndoException.class)  
public void testUndoThrowsCannotUndoException() {   
    // code to initialise 'command'

    command.undo();
}

但是,此代码未能通过JUnit测试,将抛出的(和预期的)异常报告为错误.

However, this code fails the JUnit test, reporting the thrown (and expected) exception as an error.

我正在测试的方法只有这样:

The method I'm testing has only this in the body:

public void undo() {
    throw new CannotUndoException();
}

此外,以下测试通过:

public void testUndoThrowsCannotUndoException() {
    // code to initialise 'command'

    try { 
        command.undo();
        fail();
    } catch (CannotUndoException cue){

    }
}

意味着实际上抛出了预期的异常.

Meaning that the expected exception is actually thrown.

我实际上打算改变方法以实际执行某件事,而不是仅仅抛出异常,但是我对导致问题的原因感到好奇,以免将来再次发生.

I am actually planning to change the method to actually do something, rather than just throw the exception, but it's got me curious as to what caused the problem, lest it should happen again in the future.

已进行以下检查:

  • 导入到测试用例中的CannotUndoException是正确的
  • JUnit的版本4是我的类路径上唯一的一个
  • 干净的Eclipse工作区构建并没有改变结果

我正在使用JUnit 4.1,在同一测试中,我正在使用Mockito.

I am using JUnit 4.1, and in the same test I am using Mockito.

是什么原因导致错误的故障?

What could be causing the erroneous failure?

推荐答案

我发现了问题.

我使用的TestRunner是正确的(JUnit 4),但是,我将测试类声明为:

The TestRunner I was using was the correct one (JUnit 4), however, I declared my test class as:

public class CommandTest extends TestCase

我认为这是导致测试运行程序将其视为JUnit 3测试的原因.我删除了extends TestCase并收到了预期的结果.

Which I assume is causing the test runner to treat it as a JUnit 3 test. I removed extends TestCase and received the expected results.

这篇关于使用JUnit 4的预期异常机制导致意外行为的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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