[英]Java: Calling in main implemented Interface Methods from a jUnit - Test
我有以下function
:
public static String s(B b) {
int t = b.t();
String r ="Hello ";
for(String z:s) {
boolean x=b.f(t,5);
if(x) {
r+=z;
}
}
return r;
}
其中包含B - Interface
接口B
- 方法int t() and boolean f(int a, int b)
在main
內的同一類中實現,如下所示:
public static void main(String[] args) {
A.s(new B() { //A - Class
@Override //B - Interface
public int t() {
return 15;
}
@Override
public boolean f(int a, int b) {
return true;
}
});
}
問題:當接口方法在main
中實現時,我如何測試public static String s(B b)
- jUnit - test
的函數jUnit - test
當函數要求接口作為參數時進行測試?
類稱為A
,接口: B
當您想要測試您的s()
方法時,您可以提供對實現B
接口的對象的任何引用。 您可以像在main()
方法中一樣定義一個實現接口的匿名類。 或者您也可以定義一個“普通”類來實現該接口。 所以你可以這樣寫:
public class Whatever implements B
{
/* your methods from B */
}
然后,您可以像在單元測試中使用任何其他類一樣使用此類:
@Test
public void checkSomething() {
String result = A.s(new Whatever());
Assertions.assertEquals("my string", result);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.