简体   繁体   English

如何使用 Eclipse 测试方法? (爪哇)

[英]How to test a method using Eclipse? (Java)

So i have coded a method on eclipse (java), and I want to test if it works correctly, how do I do this, because the program won't run unless it has a main header.所以我在eclipse(java)上编写了一个方法,我想测试它是否正常工作,我该怎么做,因为除非它有一个主标题,否则程序不会运行。

So I guess what im asking is how do i use a method in another code所以我想我问的是如何在另一个代码中使用一个方法

Well if your method is static you can access it via it's class name, if its a member of the class you have to create a instance of the class and call it using the instance.好吧,如果你的方法是静态的,你可以通过它的类名访问它,如果它是类的成员,你必须创建一个类的实例并使用该实例调用它。 Let's say we have this class and we want to call both methods in another class:假设我们有这个类,我们想在另一个类中调用这两个方法:

public class ClassToTest {

    public static void staticMethodToTest(){
        //Some code
    }

    public void memberMethodToTest(){
        //Some code
    }
}  

To test them you can create another class:要测试它们,您可以创建另一个类:

public class MyClass {
    //Create a main method so you can run your code
    public static void main(String[] args) {

        //Call static method
        ClassToTest.staticMethodToTest();

        //Call member
        //Create instance of class
        ClassToTest classToTestInstance = new ClassToTest();
        //Call method on instance
        classToTestInstance.memberMethodToTest();

    }
}

In the case that both classes are in different packages you have to import the ClassToTest using import package.name.ClassToTest;如果两个类都在不同的包中,您必须使用import package.name.ClassToTest;导入ClassToTest import package.name.ClassToTest;

I think you want to test the internal workings of your program, you can do this by either creating a temporary main() method, or by using JUnit testing.我认为你想测试你的程序的内部工作,你可以通过创建一个临时的main()方法或使用 JUnit 测试来做到这一点。

You can accomplish this simply by doing:您只需执行以下操作即可完成此操作:

public static void main(String[] args)
{
    //Test it here
}

and you should be able to just comment it out/remove it if it works.如果它有效,您应该能够将其注释掉/删除它。

//Have the method declared inside a class.
public MyClass(){
 public String myString(String m){
   return m;
 }
}
//Create another class for your main method and inherit from MyClass   

public MainClass extends MyClass {

public static void main(String[] args){
//Create an object obj from MyClass() 
  //and call the method on the object
     MyClass obj = new MyClass();
     System.out.println(obj.myString("hello"));
   }
}

Write the method in another class, and give it a constructor so that it can be instantiated.在另一个类中编写该方法,并为其提供一个构造函数,以便它可以被实例化。 In your main class, make an instance of the class and call your method from it.在您的主类中,创建该类的一个实例并从中调用您的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM