JUnit - 没有可运行的方法

时间:2018-03-24 13:18:09

标签: java junit

我正在尝试使用NetBeans运行junit测试的示例,但是我很想得到没有runnable方法错误,尽管据我所知我实际上有可运行的方法。 我在这里找到了这个例子:https://www.tutorialspoint.com/junit/junit_basic_usage.htm 你能告诉我如何解决这个问题吗? the screenshot of the error     包TestPackage;

public class ClassToTest {

   private String message;

   //Constructor
   //@param message to be printed

   public ClassToTest(String message){
      this.message = message;
   }

   // prints the message

   public String printMessage(){
      System.out.println(message);
      return message;
   }
}

//---------------------------------------------------------------------

package TestPackage;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class TestJuniit {

   String message = "Hello World";
   ClassToTest ClassToTest = new ClassToTest(message);

   @Test
   public void testPrintMessage() {
      assertEquals(message,ClassToTest.printMessage());
   }
}

//---------------------------------------------------------------------

package TestPackage;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {

    public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJuniit.class);

      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }

      System.out.println(result.wasSuccessful());
    }

}

2 个答案:

答案 0 :(得分:1)

我最近遇到了与IntelliJ相同的问题,原因是我的测试类没有遵循命名约定,据我所记得以“Test”或“TestCase”结尾。在你的例子中,你没有遵循这个约定,也许这就是原因?

答案 1 :(得分:0)

在IntelliJ中运行并传递给我。

我将类和测试放在同一个包中 - 一个在/ src / java下,另一个在test / java下。

package cruft;

/**
 * Created by Michael
 * Creation date 3/24/2018.
 * @link https://stackoverflow.com/questions/49465133/junit-no-runnable-methods?noredirect=1#49465133
 */
public class ClassToTest {

    private String message;
    public ClassToTest(String message){
        this.message = message;
    }

    public String printMessage(){
        System.out.println(message);
        return message;
    }
}

带有更正的测试类:

package cruft;

import org.junit.Assert;
import org.junit.Test;

/**
 * Created by Michael
 * Creation date 3/24/2018.
 * @link https://stackoverflow.com/questions/49465133/junit-no-runnable-methods?noredirect=1#49465133
 */
public class ClassToTestTest {

    @Test
    public void testPrintMessage() {
        // setup
        String message = "Hello World";
        ClassToTest classToTest = new ClassToTest(message);
        // exercise
        // assert
        Assert.assertEquals(message,classToTest.printMessage());
    }
}