简体   繁体   English

为什么在扩展TestCase类时无法找到或加载主类

[英]why cant find or load main class when extends TestCase class

I encounter a interesting error by accident and I need you help me figure it out. 我意外地遇到了一个有趣的错误,我需要你帮助我搞清楚。

as for the below code every thing is ok: 至于下面的代码,每件事都可以:

public class HelloWorld{
    public static void main(String[] args){
        System.out.println("hello world");
    }
}

then as for the follow code, something interesting come. 那么跟随代码,有趣的东西来了。

import junit.framework.TestCase;

public class HelloWorld extends TestCase{
    public static void main(String[] args){
        System.out.println("hello world");
    }
}

when I run it, it says 当我跑它时,它说

cant find or load main class. 无法找到或加载主类。

I know when jvm load HelloWorld class it will load TestCase class first. 我知道当jvm加载HelloWorld class它会首先加载TestCase class So I make the below code segment. 所以我做了下面的代码段。

public class HelloWorld {
    public static void main(String[] args) throws ClassNotFoundException{
        Class.forName("junit.framework.TestCase");
    }
}

Exception in thread "main" java.lang.ClassNotFoundException: junit.framework.TestCase 线程“main”中的异常java.lang.ClassNotFoundException:junit.framework.TestCase

I dont know why? 我不知道为什么? Maybe the TestCase class is not on my classpath ? 也许TestCase类不在我的类路径上? But as for the second code segment I ensure TestCase is on my classpath . 但至于第二个代码段,我确保TestCase在我的类路径上


So my question is: 所以我的问题是:

  1. Why can't I load TestCase class? 为什么我不能加载TestCase类?
  2. Why can't it find or load main class when extend TestCase class? 为什么在扩展TestCase类时无法找到或加载主类?

Note: I know the print helloworld function has nothing with TestCase class which used to junit test but I want to figure out the reason that bring this suprise. 注意:我知道print helloworld函数与TestCase class没有任何关系,它曾用于junit测试,但我想找出导致这种惊喜的原因。

I dont know why? 我不知道为什么? Maybe the TestCase class is not on my classpath ? 也许TestCase类不在我的类路径上? But as for the second code segment I ensure TestCase is on my classpath. 但至于第二个代码段,我确保TestCase在我的类路径上。

 Class.forName("junit.framework.TestCase"); 

returns the Class object associated with TestCase class. 返回与TestCase类关联的Class对象。 It doesn t set the classpath. 它没有设置类路径。

That's why you rise the exception : 这就是你提出异常的原因:

Exception in thread "main" java.lang.ClassNotFoundException: junit.framework.TestCase 线程“main”中的异常java.lang.ClassNotFoundException:junit.framework.TestCase

You try to load a class which is not in the classpath. 您尝试加载不在类路径中的类。

To solve your problem with Eclipse, go in the properties windows of your project, then at the left, you have the Java Build Path option, go inside and look at the libraries tab. 要解决Eclipse的问题,请进入项目的属性窗口,然后在左侧,您有Java Build Path选项,进入内部并查看库选项卡。 Here, you should add the JUnit library if you want JUnit to be in the classpath. 在这里,如果希望JUnit位于类路径中,则应添加JUnit库。

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

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