尝试赶上JUnit测试 [英] Try catch in a JUnit test

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

问题描述

我正在为已经存在很长时间的应用程序编写单元测试.我需要测试的一些方法是这样构建的:

I'm writing unit tests for an application that already exists for a long time. Some of the methods I need to test are build like this:

public void someMethod() throws Exception { 
   //do something 
}

如果要测试这些方法,则必须在单元测试中编写如下内容:

If I want to test these methods I have to write something like this in my unit test:

@Test
public void someTest() {
   try {
      someMethod();
   }
   catch (Exception e) {
      e.printStackTrace();
   }
}

这样做是一种好习惯吗?还是有其他方法可以测试这些方法?

Is it a good practice to do this? Or is there an other way to test these methods?

我在Internet上进行了一些研究,发现了一些带有@Rule批注和@Test(expected=Exception.class)的解决方案,但这是行不通的(Eclipse不断在测试中显示someMethod()行是错误的). 我不知道这些是否是好的解决方案,因为对于整个单元测试来说,我还是一个新手.

I did some research on the internet and I found a few solutions with the @Rule annotation and @Test(expected=Exception.class), but that's not working (Eclipse keeps showing the someMethod() line in the test as wrong). I don't know if these are good solutions, because I'm pretty new to the whole unit testing story.

如果对此有很多了解的人可以帮助我,我将非常感激.

If someone who knows a lot about this could help me out, I would be really thankful.

推荐答案

由于Exception是已检查的异常,因此您可以:

Since Exception is a checked exception, you either:

  • 必须在try...catch语句中捕获异常,或者
  • 声明要在方法本身中引发的异常.
  • Have to catch the exception in a try...catch statement, or
  • Declare the exception to be thrown in the method itself.

您在那里的工作正常,但是我个人的喜好是声明要抛出的异常.这样,如果在测试运行期间抛出了我没想到的异常,则测试将失败.

What you have up there works fine, but my personal preference is to declare the exception to be thrown. This way, if an exception I'm not expecting is thrown during the run of the test, the test will fail.

@Test
public void someTest() throws Exception {
    // dodgy code here
}

如果我们需要查看是否抛出了特定的异常,则可以选择使用@Rule或将值直接添加到@Test批注中.

If we need to see if a specific exception is thrown, then you have the option of using @Rule or adding the value to the @Test annotation directly.

@Test(expected = FileNotFoundException.class)
public void someTest() throws Exception {
    // dodgy code here
}

在JUnit 5中,您可以利用

In JUnit 5, you can leverage Assertions.assertThrows to accomplish the same thing. I'm less familiar with this overall since it's not yet GA at the time of editing, but it appears to accept an Executable coming from JUnit 5.

@Test
public void someTest() {
    assertThrows(FileNotFoundException.class, () ->
         { dodgyService.breakableMethod() };
}

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

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