![](/img/trans.png)
[英]How can I correctly create a JUnit test method testing a service method that needs a Pageable object for pagination?
[英]JUnit testing can't find the method that I want to test
以下是(不完整的)一段包含方法“ IntRelation”的代碼,我要測試該方法是否引發異常。
public abstract class IntRelation {
public IntRelation(final int n) throws IllegalArgumentException {
if (n < 0) {
throw new IllegalArgumentException ("Parameter in precondition violated.");
}
}
}
下面是(不完整的)一段代碼,其中包含“ IntRelation”方法的測試用例。
public abstract class IntRelationTestCases {
protected IntRelation instance;
@Test
public void testException0() {
Class expected = IllegalArgumentException.class;
instance.IntRelation(-1);
}
}
我遇到的問題是,在第二段代碼中,NetBeans / JUnit說它找不到方法“ IntRelation”。 我究竟做錯了什么?
確實如此。 這是因為您正在像調用方法一樣調用構造函數。 不要那樣做
我想您想做的是instance = new IntRelation(...);
或者您的意思是實際上是一種方法,在這種情況下,由於缺少返回類型,因此未正確定義它。
在這方面, public void IntRelation(...)
應該這樣做。
但是隨后您將遇到一個未實例化的instance
,該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() { };
}
然后從測試該單元的測試中照常調用它。
@Test
public void testException0() {
...
instance.IntRelation(-1);
}
不過,我要說的是,命名一個與其類名相同的方法可能會造成混亂。 另外,以Java命名約定使用前導大寫字母來命名方法是違背的。 首字母應小寫,其余字母應為駝色。 例如, thisIsTheCorrectWay(...)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.