如何从JUnit assertEquals()方法获取输出并将其放入变量中? [英] How to get an output from JUnit assertEquals() method and put it into a variable?

查看:523
本文介绍了如何从JUnit assertEquals()方法获取输出并将其放入变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一个JUnit测试用例,用于测试一个简单的类.基本上,该类仅包含一个称为"sum"的方法,该方法返回两个数字的和.要测试这是否正确,我使用以下方法:Assert.assertEquals(2, my_object.sum(1, 2));结果显示在Eclipse的选项卡中的故障跟踪"部分中.该消息显示:junit.framework.AssertionFailedError: expected:<2> but was:<3>.是否有可能获得此消息并将其放入String变量?

I have a JUnit test case here to test a simple class. Basically the class contains just one method called 'sum' that returns the sum of two numbers. To test if this is right I use the following method: Assert.assertEquals(2, my_object.sum(1, 2)); The result displays in a tab on eclipse, in a section called "Failure Trace". The message says: junit.framework.AssertionFailedError: expected:<2> but was:<3>. Is it possible to get this message and put it into a String variable?

推荐答案

来自Java文档assertEquals将

From the Java doc assertEquals will

断言两个对象相等.如果不是,则为AssertionError 没有消息被抛出.如果期望和实际为空,则为 被认为是平等的.

Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null, they are considered equal.

条件失败时,您必须赶上AssertionError.

You have to catch AssertionError when your condition fails.

尝试以下代码:

 @Test
    public void myTest() throws Exception{
        String assertionError = null;
        try {
            Assert.assertEquals(2,3);
        }
        catch (AssertionError ae) {
            assertionError = ae.toString();
        }
        System.out.println(assertionError);

    }

输出:

java.lang.AssertionError:预期:< 2>,但是:< 3>

java.lang.AssertionError: expected:<2> but was:<3>

有关AssertionError的更多信息,请访问java doc: AssertionError 声明

For more info about AssertionError visit java doc : AssertionError and Assert

这篇关于如何从JUnit assertEquals()方法获取输出并将其放入变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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