本文介绍了为什么使用JUnit在Java类中编译对fail()的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎不应该编译和运行,因为Object没有fail()方法.在编译时发生了什么时髦的事情? (我正在使用NetBeans):

This seems like it shouldn't compile and run as Object does not have a fail() method. At compile time is something funky happening? (I am using NetBeans):

import static org.junit.Assert.*;
import org.junit.Test;

public class Test {

    @Test
    public void hello() {
        fail();

    }
}

此致

Guido

推荐答案

您的import static行将Assert类的所有静态成员导入到编译单元的静态名称空间中. fail()调用引用Assert.fail().

Your import static line imports all static members of the Assert class into the static namespace of your compilation unit. The fail() call refers to Assert.fail().

您对定义fail()的位置所遇到的困惑正是为什么我通常不建议使用import static的原因.在我自己的代码中,我通常导入该类并使用它来调用静态方法:

The confusion you are experiencing regarding where fail() is defined is precisely why I don't usually recommend using import static. In my own code, I usually import the class and use it to invoke the static methods:

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

public class Test {

    @Test
    public void hello() {
        Assert.fail();
    }
}

更具可读性.

但是,作为,将import static用于JUnit的断言是相当普遍的做法.当您编写和阅读足够的JUnit测试时,知道断言方法的来源将成为第二自然.

However, as JB Nizet points out, it is fairly common practice to use import static for JUnit's assertions; when you write and read enough JUnit tests, knowing where the assertion methods come from will become second nature.

这篇关于为什么使用JUnit在Java类中编译对fail()的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 11:14