下面是包含"IntRelation"方法的(不完整的)代码,我想测试它是否抛出异常.
public abstract class IntRelation {
public IntRelation(final int n) throws IllegalArgumentException {
if (n < 0) {
throw new IllegalArgumentException ("Parameter in precondition violated.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
下面是包含"IntRelation"方法的测试用例的(不完整)代码.
public abstract class IntRelationTestCases {
protected IntRelation instance;
@Test
public void testException0() {
Class expected = IllegalArgumentException.class;
instance.IntRelation(-1);
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,在第二段代码中,NetBeans/JUnit说它找不到方法"IntRelation".我究竟做错了什么?
确实如此.这是因为你正在调用一个构造函数,就像它是一个方法; 不要那样做.
我想你想做的是 instance = new IntRelation(...);
或者你的意思是实际上是一种方法,在这种情况下,由于缺少返回类型,你没有正确定义它.
public void IntRelation(...) 应该在这方面做到这一点.
但是你会遇到一个未经实例化的问题,这个问题instance应该引导你进入NullPointerException.
如果您想要设置一些数据来测试它,那么使用注释来准备测试就是一个好习惯.
例:
@Before
public void setUp() {
// Since your class is abstract you can do it like this
// to get an anonymous class you can test that non-abstract
// method with...
instance = new IntRelation() { };
}
Run Code Online (Sandbox Code Playgroud)
然后从测试测试该单元照常调用它.
@Test
public void testException0() {
...
instance.IntRelation(-1);
}
Run Code Online (Sandbox Code Playgroud)
我会说,但是,命名一个与其类名相同的方法似乎可能令人困惑.另外,用Java命名约定命名一个带有前导上限的方法; 第一封信应该是小写的,其余的应该是骆驼.例如,thisIsTheCorrectWay(...).
| 归档时间: |
|
| 查看次数: |
1352 次 |
| 最近记录: |