如何在 Eclipse 中快速测试 Java 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27245914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:01:55  来源:igfitidea点击:

How to quickly test a Java-method in Eclipse?

javaeclipseunit-testingdebuggingtesting

提问by Edward

I have a simple method in My Java-code, e.g.

我的 Java 代码中有一个简单的方法,例如

private int specialAdd (int a, int b) {
  if(a < 100) {
    return 100 * a + b;
  } else {
    return a + b;
  }
}

Is there a way to "run/debug selected code" with given parameter values in eclipse? I'd really like to run only this method and view the result for a couple a values for aand b.

有没有办法在 eclipse 中使用给定的参数值“运行/调试选定的代码”?我真的很想只运行此方法并查看结果为一对夫妇一个值ab

采纳答案by aioobe

Is there a way to "run/debug selected code" with given parameter values in eclipse?

有没有办法在 eclipse 中使用给定的参数值“运行/调试选定的代码”?

No, Eclipse needs a regular mainmethod or a @Testmethod as an entry point.

不,Eclipse 需要一个常规main方法或一个@Test方法作为入口点。

When I want to do a "one off" mini test, what I usually do is

当我想做一个“一次性”的小测试时,我通常做的是

class YourClass {
    private int specialAdd (int a, int b) {
       if(a < 100) {
           return 100 * a + b;
       } else {
           return a + b;
    }

    public static void main(String[] args) {
        System.out.println(new YourClass().specialAdd(10, 100));
    }
}

and then run (or debug) the current class. (Pro tip: type mainand hit Ctrl+Spaceto expand it to a full main method)

然后运行(或调试)当前类。(专业提示:输入main并点击Ctrl+Space将其扩展为完整的主要方法)



As of JDK 9, you can also use jshellfor this kind of testing:

从 JDK 9 开始,您还可以jshell用于此类测试:

$ ./jshell
|  Welcome to JShell -- Version 1.9.0-internal
|  Type /help for help

-> int specialAdd(int a, int b) {
>>     if (a < 100) {
>>         return 100 * a + b;
>>     } else {
>>         return a + b;
>>     }
>> }
|  Added method specialAdd(int,int)

-> specialAdd(10, 5);
|  Expression value is: 1005
|    assigned to temporary variable  of type int

回答by MageXellos

Use Junit without input parameters and output parameters:

使用没有输入参数和输出参数的 Junit:

@Test 
private void specialAdd () {
  // provide the value of a and b
  int a = 30;
  int b = 20;
  if(a < 100) {
    System.out.println("100 * a + b =" + 100 * a + b);
  } else {
    System.out.println("a + b =" + a + b);
  }
}

Then, choose the method name "specialAdd" and click the right button in your mouse,choose run --> run junit test.

然后,选择方法名称“specialAdd”并单击鼠标右键,选择run --> run junit test。

回答by SMA

I would recommend you to use test frameworks like testng/junit where you can assert values returned by your method and you could create repeatable tests with them.

我建议您使用 testng/junit 之类的测试框架,您可以在其中断言方法返回的值,并且可以使用它们创建可重复的测试。

But if you want to test it simply with main, you could do the following:

但是如果你想简单地用 main 测试它,你可以执行以下操作:

 public static void main(String args[]) {
       int number = specialAdd(99, 1);
       if (number != 9901) {
            System.out.println("Expected: " + 9901 + " Actual: " + number);
       }
       if (args.length >= 2) {//with system args
           int number1 = Integer.parseInt(args[0]);
           int number2 = Integer.parseInt(args[1]);
           number = specialAdd(number1, number2);
           if (number != ...) {} 
       }
 }

回答by Rafa Romero

Configure your method as unitary test, with JUnit for example. By this way you will be able to test the methods separately.

将您的方法配置为单一测试,例如使用 JUnit。通过这种方式,您将能够分别测试这些方法。

To use jUnit, add the @Testannotation to your method. You should add to your method an Asset sentence yo check your method operation/perfomance. For example:

要使用 jUnit,请将@Test注释添加到您的方法中。您应该在您的方法中添加一个 Asset 语句,以检查您的方法操作/性能。例如:

   @Test
   public void testHelloWorld() 
   {
      h.setName("World");
      assertEquals(h.getName(),"World");
      assertEquals(h.getMessage(),"Hello World!");
   }

Then click on the method and Run as > JUnit Test:

然后单击该方法并Run as > JUnit Test

enter image description here

enter image description here

You can download JUnit via Maven:

您可以通过 Maven 下载 JUnit:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
</dependency>

回答by Dawood ibn Kareem

First up, you don't want to test a private method like this directly. If it were public, you'd write two JUnit test cases, one for each of the possible paths through your method.

首先,您不想直接测试这样的私有方法。如果它是公开的,您将编写两个 JUnit 测试用例,一个用于通过您的方法的每个可能路径。

public class YourClassTest {

    private YourClass toTest = new YourClass();

    @Test
    public void specialAddMultiplesSmallFirstAddendBy100() {
        int result = toTest.specialAdd(99, 7);
        assertEquals(9907, result);
    }

    @Test
    public void specialAddDoesNotIncreaseLargeFirstAddend() {
        int result = toTest.specialAdd(100, 7);
        assertEquals(107, result);
    }
}

JUnit will record a failure for each of these test cases, if the two arguments to assertEqualsare not equal. This enables these tests to be added to a battery of unit tests and automated.

如果 t 的两个参数assertEquals不相等,JUnit 将为每个测试用例记录一个失败。这使这些测试能够添加到单元测试中并自动化。

But since it's private, you should instead use a similar strategy to test it via whichever method calls it. Presumably there is somepublic method in your class, that calls specialAdd- by testing that public method, you will implicitly test specialAddtoo.

但由于它是私有的,您应该使用类似的策略通过调用它的任何方法来测试它。大概你的类中有一些公共方法,它调用specialAdd- 通过测试该公共方法,你也将隐式测试specialAdd

回答by Vishu

  private static int specialAdd (int a, int b) {
      if(a < 100) {
        return 100 * a + b;
      } else {
        return a + b;
      }
    }
  public static void main(String[] args) {
    System.out.println("" + specialAdd(10,20));
    System.out.println("" + specialAdd(11,21));
    System.out.println("" + specialAdd(12,23));
  }

This is how you can run the application and see the output. If you want to debug than first mark the breakpoints. Than right click your java class and select 'Debug as'-> java application. You will see your cursor moving through breakpoints when clicking step over from the tool bar.

这是您运行应用程序并查看输出的方式。如果要调试,请先标记断点。然后右键单击您的 Java 类并选择“调试为”-> Java 应用程序。单击工具栏上的 step over 时,您将看到光标在断点之间移动。

回答by Jonas Michel

In Eclipse you can create a Scrapbook page (an file with the extension .jpage)

在 Eclipse 中,您可以创建一个剪贴簿页面(扩展名为 .jpage 的文件)

In there you can write java code an execute like it was in a Method.

在那里,您可以编写 Java 代码并像在方法中一样执行。

https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-create_scrapbook_page.htm

https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-create_scrapbook_page.htm

For Example create a test.jpagein the package with the class and method you want to test. In there write your Java-Code

例如test.jpage,使用您要测试的类和方法在包中创建一个。在那里写你的 Java 代码

int a = ..., b = ...;
if(a < 100) {
    return 100 * a + b;
} else {
    return a + b;
}

or you can call Methods of your class.

或者你可以调用你的类的方法。

com.mycomp.TestedClass testedInstance = new com.mycomp.TestedClass();
for(int a=0,b=0; b < 100 && a < 100; a++,b++) {
    System.out.println(testedInstance.specialAdd(a,b));
}

Sadly imports in this file have to be written out. You can run your written code by selecting it > rigth click > execute.

遗憾的是,必须写出此文件中的导入。您可以通过选择 > 右键单击​​ > 执行来运行您编写的代码。