Reputation:
as the title states, i want to test the following Method:
Class A:
private List<String> s;
public A() {
s = new ArrayList<String>();
s.add("Gregor");
s.add("Example");
s.add("Example2");
}
public String argr(B b) { //B-> Interface
int t = b.t();
String r = "Hello ";
for(String z:s ) {
boolean x = b.f(t, 5);
if(x) {
r += z;
}
}
return r;
}
With the Interface B:
public interface B {
int t();
boolean f(int t, int i);
}
The Testing:
class Example{
public B b;
private A example = new A();
@Test
void test() {
//assert(example .s() == "Hello GregorExampleExample2");
System.out.println(example .s(b));
//bsp.A(c);
}
}
The Issue: method: b, requires an Interface
as a parametere, the interface could be implemented via this Method: Class A implements B{}
Problem: When testing it doesn't recognize the interface implemented Methods in the Class A.
Question 1: How do you jUnit test an Method with an interface as a parameter?
Question 2: Do you need to implement the interface method in the jUnit test class, for it to work?
Upvotes: 0
Views: 2400
Reputation: 479
You can create an anonymous class like this for every test case:
b = new B() {
@Override
public int t() {
return 0;
}
@Override
public boolean f(int t, int i) {
return false;
}
};
Just replace the return values with what suits your test case, but try to avoid putting any logic in the class (since then you would have to test it aswell).
If you don't want to implement the interface for every test case, another possibility is using Mockito to mock your interface:
B mock = Mockito.mock(B.class);
Mockito.when(mock.f(Mockito.anyInt(), Mockito.anyInt())).thenReturn(false);
Upvotes: 3