草庐IT

java - 检查方法在应用于值列表的任何元素时是否抛出异常

coder 2024-03-31 原文

我想为解析器编写单元测试,并想检查它是否正确地为列表中的所有输入字符串抛出异常。据我了解,JUnit 的标准方法是为每种情况编写单独的测试方法:

public final class ParseFailureTest1 {
    @Test(expected = ParseException.class)
    public void testParseFailure1() throws Exception {
        Parser.parse("[1 2]"); // Missing comma
    }

    @Test(expected = ParseException.class)
    public void testParseFailure2() throws Exception {
        Parser.parse("[1, 2,]"); // Additional commas
    }
}

但由于我想对 20 或 50 个不同的字符串应用相同的测试,这似乎不切实际。

另一种方法是使用 catch block 显式检查异常:

public final class ParseFailureTest2 {
    @Test
    public void testParseFailure() throws Exception {
        List<String> documents = Arrays.asList(
            "[1 2]", // Missing comma
            "[1, 2,]"); // Additional commas

        for (String document : documents) {
            try {
                Parser.parse(document);

                throw new AssertionError("Exception was not thrown");
            } catch (ParseException e) {
                // Expected, do nothing.
            }
        }
    }
}

但这是容易出错的,我不会得到任何关于预期的异常的信息,如果抛出不同的异常,它将被视为测试错误而不是失败。

我的解决方案是使用类似于下面的 expectException 的方法:

public final class ParseFailureTest3 {
    @Test
    public void testParseFailure() throws Exception {
        List<String> documents = Arrays.asList(
            "[1 2]", // Missing comma
            "[1, 2,]"); // Additional commas

        for (final String document : documents) {
            expectException(ParseException.class, new TestRunnable() {
                @Override
                public void run() throws Throwable {
                    Parser.parse(document);
                }
            });
        }
    }

    public static void expectException(Class<? extends Throwable> expected, TestRunnable test) {
        try {
            test.run();
        } catch (Throwable e) {
            if (e.getClass() == expected) {
                return; // Expected, do nothing.
            } else {
                throw new AssertionError(String.format("Wrong exception was thrown: %s instead of %s", e.getClass(), expected), e);
            }
        }

        throw new AssertionError(String.format("Expected exception was not thrown: %s", expected));
    }

    public interface TestRunnable {
        void run() throws Throwable;
    }
}

在 JUnit 框架或相关库中是否有用于该目的的方法,或者您会建议一种不同的方法(或我拒绝的方法之一)来解决这个问题?

最佳答案

将 JUnit4 用于参数化测试功能。以下代码应该可以工作。

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(value = Parameterized.class)
public class ParseTest {

    private String parseValue;

    public ParseTest(String parseValue) {
        this.parseValue = parseValue;
    }

    @Parameters
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][] { { "[1 2]" }, { "[1,2,]" } };
        return Arrays.asList(data);
    }

    @Test(expected = ParseException.class)
    public void testParseFailure1() throws Exception {
        Parse.parse(parseValue);
    }

}

有关更多信息,请参阅 http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/

关于java - 检查方法在应用于值列表的任何元素时是否抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20453450/

有关java - 检查方法在应用于值列表的任何元素时是否抛出异常的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  8. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  9. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  10. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

随机推荐