Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly test a Java-method in Eclipse?

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

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 a and b.

like image 734
Edward Avatar asked Dec 02 '14 09:12

Edward


2 Answers

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

No, Eclipse needs a regular main method or a @Test method as an entry point.

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 main and hit Ctrl+Space to expand it to a full main method)


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

$ ./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 $2 of type int
like image 98
aioobe Avatar answered Sep 19 '22 23:09

aioobe


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

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

   @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:

enter image description here

You can download JUnit via Maven:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
</dependency>
like image 35
Rafa Romero Avatar answered Sep 19 '22 23:09

Rafa Romero