JUnit 测试异常 [英] JUnit Testing Exceptions

查看:36
本文介绍了JUnit 测试异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的是 Java 新手.

I'm really new to java.

我正在一个构造函数上运行一些 JUnit 测试.构造函数是这样的,如果它的参数之一被赋予一个 null 或一个空字符串,它应该抛出一个异常.

I'm running some JUnit tests on a constructor. The constructor is such that if it is given a null or an empty string for one of its parameters, it's supposed to throw an exception.

当我在 JUnit 中使用 null 或空字符串参数测试此构造函数时,我得到一个红色条,即使我几乎 100% 确定构造函数方法确实在将此类参数传递给它.

When I test this constructor in JUnit with a null or an empty string parameter, I get a red bar, even though I'm almost 100% sure that the constructor method does indeed throw an exception when such parameters are passed in to it.

如果该方法以预期的方式抛出异常,JUnit 中不应该有一个绿色条吗?或者是当您应该在异常抛出按预期方式工作时获得红色条时?

Shouldn't there be a green bar in JUnit if the method throws an exception the way it is supposed to? Or is it that when you are supposed to get a red bar when the exception throwing works the way it is supposed to?

推荐答案

@Test(expected = Exception.class)  

告诉 Junit 异常是预期的结果,因此在抛出异常时将通过测试(标记为绿色).

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

为了

@Test

如果抛出异常,Junit 会认为测试失败,假设它是一个未经检查的异常.如果检查异常,它将不会编译,您将需要使用其他方法.这个链接可能会有所帮助.

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

这篇关于JUnit 测试异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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