按照答案中的建议,为接口创建实现类并对其进行测试,例如我在您的ABC 接口中修改了getSrc 方法,如下所示:
import java.util.ArrayList;
import java.util.List;
public interface ABC<T, D, K, V> {
default List<String> getSrc(DEF def, XYZ xyz) {
final List<String> defaultList = new ArrayList<>();
defaultList.add("default");
defaultList.add("another-default");
return defaultList;
}
}
为此创建了一个实现类,您可以选择创建另一个调用超级方法的方法并为两者编写@Test,就像我一样:
import java.util.List;
public class ABCImpl implements ABC<String, Integer, String, Integer> {
public List<String> getSrcImpl(DEF def, XYZ xyz) {
final List<String> list = getSrc(def, xyz);
list.add("implementation");
return list;
}
}
实现对应的Test类如下:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.contains;
import java.util.Collection;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class ABCImplTest {
private ABCImpl abcImpl;
@Before
public void setup() {
abcImpl = new ABCImpl();
}
@Test
public void testGetSrc() throws Exception {
List<String> result = abcImpl.getSrc(new DEF(), new XYZ());
assertThat((Collection<String>) result, is(not(empty())));
assertThat(result, contains("default", "another-default"));
}
@Test
public void testABCImplGetSrc() throws Exception {
List<String> result = abcImpl.getSrcImpl(new DEF(), new XYZ());
assertThat((Collection<String>) result, is(not(empty())));
assertThat(result, contains("default", "another-default", "implementation"));
}
}