I have the following 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;
}
Which takes in B - Interface
The Interface B
- Methods int t() and boolean f(int a, int b)
were implemented in the same class within main
as the following:
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;
}
});
}
Issue : How can i test the public static String s(B b)
- function from a jUnit - test
when the function asks for a interface as a parameter, when the interface methods were implemented in main
?
The Class is called A
, Interface: B
When you want to test your s()
method you can provide any reference to an object which implements the B
interface. You can define an anonymous class which implements the interface as you did in your main()
method. Or you can define a "normal" class which implements the interface as well. So you can write something like this:
public class Whatever implements B
{
/* your methods from B */
}
Then you use this class like any other class inside your unit test:
@Test
public void checkSomething() {
String result = A.s(new Whatever());
Assertions.assertEquals("my string", result);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.