In scala, there is a trait like
trait Client {
def get(requests: Seq[Request]): Future[Seq[Response]]
}
How to implement the class in Java with some fake implementation like return Future.successful(List.empty())?
I tried
class KVClient implements Client {
#Override
public Future<Seq<Response>> get(Seq<Request> requests) {
return Future.successful(List.empty());
}
But it didn't compile. Error is "KVClient is not abstract and does not override abstract method get(Seq) in Client"
if i understood you correctly you are trying to return result or error of response future.
Simple solution would be:
public CompletableFuture<Optional<?>> send() throws ExecutionException, InterruptedException {
final CompletableFuture<Optional<?>> optionalCompletableFuture = CompletableFuture.supplyAsync(() -> "")
.thenApplyAsync(f -> {
if (isError(f)) {
return Optional.empty();
}
return Optional.of(f);
});
return optionalCompletableFuture;
}
Related
I want to test a method which returns an Optional client in it.
I want to test the scenario when client is empty.This is not a working code but overall it looks like this
public Optional<String> doSomething(String place) {
Optional<Client> client = Optional.empty();
try {
client = Optional.ofNullable(clientHelper.get(place));
} catch (Ex ex) {
log.warn("Exception occured:", ex);
}
return client.isPresent() ? Optional.ofNullable(client.get().getPlaceDetails(place)) : Optional.empty();
}
I have a helper class clientHelper which returns a client based on place if exists, if not it throws exception.
For test, this is what I came up with
#Test
public void testClientHelper(){
ClientHelper clientHelper = Mockito.mock(ClientHelper.class);
Optional<Client> client = Optional.empty();
Mockito.when(Optional.ofNullable(clientHelper.get("IN"))).thenReturn(client);
assertEquals( doSomething("IN"), Optional.empty())
}
But it returns exception -
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Optional cannot be returned by get()
get() should return Client
I have been following this link Mockito error with method that returns Optional<T>
your problem here is that you are calling when with something that isn't a mock. You are passing it an Optional.
If I understand what you are trying to do here, the clientHelper is passed to the object with the doSomething method and you want to mock it for testing purposes. If that's the case it'd more typically look like this:
interface ClientHelper {
Client get(String place) throws Ex;
}
class ClassUnderTest {
private final ClientHelper clientHelper;
public ClassUnderTest(ClientHelper helper) {
this.clientHelper = helper;
}
public Optional<String> doSomething(String place) {
try {
return Optional.ofNullable(clientHelper.get(place).getPlaceDetails(place));
} catch (Ex ex) {
log.warn("Exception: " + ex);
return Optional.empty();
}
}
}
#Test
void testFullHelper() {
Client client = mock(Client.class);
when(client.getPlaceDetails("IN")).thenReturn("Details");
ClientHelper helper = mock(ClientHelper.class);
when(helper.get("IN")).thenReturn(client);
ClassUnderTest obj = new ClassUnderTest(helper);
assertEquals("Details", obj.doSomething("IN"));
}
I'm having some trouble when trying to translate Java code with nested generics to Kotlin. Take this Java SSCCE as an example (please note the relation between S and T):
public class JavaTest {
private class JavaObjectContainer<S> {
public S obj;
}
private abstract class JavaSampleClass<S, T extends JavaObjectContainer<S>> {
private Class<S> type;
public JavaSampleClass(Class<S> type) {
this.type = type;
}
public Class<S> getType() {
return type;
}
public abstract void callMethod(S s);
}
private class JavaChildSampleClass extends JavaSampleClass<String, JavaObjectContainer<String>> {
public JavaChildSampleClass() {
super(String.class);
}
#Override
public void callMethod(String s) {}
}
private class JavaTestContainer {
private Map<Class<?>, JavaSampleClass> sampleClasses;
public JavaTestContainer() {
this.sampleClasses = new HashMap<>();
}
public void registerJavaSampleClass(JavaSampleClass javaSampleClass) {
sampleClasses.put(javaSampleClass.getType(), javaSampleClass);
}
public void callMethod(Object obj) {
sampleClasses.get(obj.getClass()).callMethod(obj);
}
}
public void test() {
JavaTestContainer javaTestContainer = new JavaTestContainer();
javaTestContainer.registerJavaSampleClass(new JavaChildSampleClass());
javaTestContainer.callMethod("Hola");
}
}
Think of this SSCCE as an implementation of a generic factory pattern, where the user registers multiple JavaSampleClass whose methods can be invoked in the future.
As Kotlin does not provide an alternative to wildcards, I have tried the following approach:
class KotlinTest {
private class KotlinObjectContainer<S> {
var obj : S? = null
}
private open class KotlinSampleClass<S, T : KotlinObjectContainer<S>>(var type: Class<S>) {
fun callMethod(s : S) {}
}
private class KotlinChildSampleClass : KotlinSampleClass<String, KotlinObjectContainer<String>>(String::class.java)
private inner class KotlinTestContainer {
private val sampleClasses: MutableMap<Class<Any>, KotlinSampleClass<Any, KotlinObjectContainer<Any>>> = mutableMapOf()
fun registerKotlinSampleClass(kotlinSampleClass: KotlinSampleClass<Any, KotlinObjectContainer<Any>>) {
sampleClasses.put(kotlinSampleClass.type, kotlinSampleClass)
}
fun callMethod(obj : Any) {
sampleClasses[obj.javaClass]?.callMethod(obj)
}
}
fun test() {
val kotlinTestContainer = KotlinTestContainer()
// Exception!
kotlinTestContainer.registerKotlinSampleClass(KotlinChildSampleClass())
kotlinTestContainer.callMethod("Hello")
}
}
The above code throws the following exception in the IDE:
Type mismatch.
Required: KotlinTest.KotlinSampleClass<Any, KotlinObjectContainer<Any>>
Found: KotlinTest.KotlinChildSampleClass
I have been thinking of declaring sampleClasses map as
MutableMap<*, *>
But then, how can I initialize it? Also, as * represents an out-projected parameter, the IDE shows me an error when trying to put new values in the map.
How can I overcome this issue? I'm quite certain that I'm missing something...
As Kotlin does not provide an alternative to wildcards...
I have been thinking of declaring sampleClasses map as
MutableMap<*, *>
For this case * corresponds to wildcards perfectly well. If you have Class<?> in Java, you want Class<*> in Kotlin, not Class<Any> or *.
private val sampleClasses: MutableMap<Class<*>, KotlinSampleClass<*, *>> = mutableMapOf()
fun registerKotlinSampleClass(kotlinSampleClass: KotlinSampleClass<*, *>) {
sampleClasses.put(kotlinSampleClass.type, kotlinSampleClass)
}
#Suppress("UNCHECKED_CAST")
fun callMethod(obj : Any) {
(sampleClasses[obj.javaClass] as KotlinSampleClass<Any, *>?)?.callMethod(obj)
}
The only reason you don't need the cast in callMethod in Java is because you are using raw types (as Turing85's comment mentions) and the compiler basically gives up on type checking.
I have Utils class with method which throws exception when given data are incorrect.
I have also Service which uses this method, but the data are always generated in way that they will be correct during call. Data are generated by another utils class.
I understand that I should throw this exception from Utils class - but I can't throw it from Service - so I have to catch it.
How can I test this, simulate this exception?
All actions on this data are in private methods.
I want to avoid PowerMock, because I heard that it's a sign of bad design.
So the question is, how to implement this in good design?
From your description it looks like this:
class Service {
public void someMethod() {
Data data = AnotherUtils.getData();
try {
Utils.method(data); // exception never thrown
} catch(Exception e) {
// how to test this branch?
}
}
}
The goal would be something like this:
interface DataProvider {
Data getData();
}
interface DataConsumer {
void method(Data data);
}
class Service {
private final DataProvider dataProvider;
private final DataConsumer dataConsumer;
public Service(DataProvider dataProvider, DataConsumer dataConsumer) {...}
public void someMethod() {
Data d = dataProvider.getData();
try {
dataConsumer.method(data);
} catch(Exception e) {
}
}
}
This technique is called dependency injection.
Then, when testing, you can simply provide a mock implementation for this DataProvider interface that does return faulty data:
#Test(expected=Exception.class)
public void myTest() {
DataProvider badDataProvider = () -> new BadData(); // Returns faulty data
Service service = new Service(badDataProvider, Utils.getConsumer());
service.someMethod(); // boom!
}
For the non-testing code, you could simply wrap the utils classes you already have in these interfaces:
class AnotherUtils {
public static Data getData() {...}
public static DataProvider getProvider() {
return AnotherUtils::getData;
}
}
...
Service service = new Service(AnotherUtils.getProvider(), Utils.getConsumer());
Here is an approach where you want to introduce Dependency Injection, but for whatever reason you don't want to change legacy code.
Say you have some static utility method like so:
class Utils{
public static Something aMethod(SomethingElse input) throws AnException{
if(input.isValid())
return input.toSomething();
throw new AnException("yadda yadda");
}
}
And you have a class that uses that utility method. You can still inject it with a FunctionalInterface.
#FunctionalInterface
interface FunctionThrowsAnException<K,V> {
V apply(K input) throws AnException;
}
class Service {
private final FunctionThrowsAnException<SomethingElse,Something> func;
Service(FunctionThrowsAnException<SomethingElse,Something> func){
this.func = func;
}
Something aMethod(SomethingElse input){
try{
return func.apply(input);
}catch(AnException ex){
LOGGER.error(ex);
}
}
}
Then use it like this:
new Service(Utils::aMethod).aMethod(input);
To test it:
new Service(x -> { throw new AnException("HA HA"); }).aMethod(input);
I have this class that wraps an object:
public class MyWrapper implements MyInterface {
private MyInterface wrappedObj;
public MyWrapper(MyInterface obj) {
this.wrappedObj = obj;
}
#Override
public String ping(String s) {
return wrappedObj.ping(s);
}
#Override
public String doSomething(int i, String s) {
return wrappedObj.doSomething(i, s);
}
// many more methods ...
}
Now I want to add complex exception handling around the wrappedObj call.
It is the same for all the methods.
How do I avoid repeating the same exception handling code over and over?
If your exception handling is fully generic you could implement the wrapper as InvocationHandler:
public class ExceptionHandler implements java.lang.reflect.InvocationHandler {
public ExceptionHandler(Object impl) {
impl_ = impl;
}
#Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return method.invoke(impl_, args);
}
catch (Exception e) {
// do exception handling magic and return something useful
return ...;
}
}
private Object impl_;
}
and then wrap it around an instance as follows:
MyInterface instance = ...
MyInterface wrapper = (MyInterface)java.lang.reflect.Proxy.newProxyInstance(
instance.getClass().getClassLoader(),
new Class[] { MyInterface.class },
new ExceptionHandler(instance));
wrapper.ping("hello");
If you want to avoid the cost of reflection, than just use a router function.
#Override
public String ping(String s) {
return (String) call("ping");
}
private Object call(String func) {
try {
switch(func) {
case "ping": return wrappedObj.ping(s);
// ... rest of functions ... //
}
} catch(Exception e) {
log(e);
}
}
The compiler can than effectively just jump to the function without pulling up Object specs or handlers. (A smart enough compiler may even just compile this to identical execution code as your current code, especially if you can cut the cast by always returning the same kind of object)
If you don't care about the thread and just want a default exception handler...
For the whole Java Runtime, call Thread.setDefaultUncaughtExceptionHandler
For a ThreadGroup, override ThreadGroup.uncaughtException
For a single Thread, call Thread.setUncaughtExceptionHandler
The advantage to a default handler, is that you can then add specific error handlers where needed, but the down side is you do lose the executing thread on error.
Using Guava Listenable Futures
Assume I have the following class:
public class FooService {
ListenableFuture<Foo> getFoo() {
//code to create callable, then
return listeningExecutorService.submit(fooCallable);
}
}
and the following class:
public class BarService {
ListenableFuture<Bar> getBar(Foo foo) {
//code to create callable, then
return listeningExecutorService.submit(barCallable);
}
}
Note that getBar requires a Foo in the parameters.
If I want to chain these two operations together I would write a transformer function like this:
AsyncFunction<Foo, Bar> fooToBar = new AsyncFunction<Foo, Bar>() {
#Override
ListenableFuture<Bar> apply(Foo resultantFoo) {
return barService.get(resultantFoo);
}
};
and then apply the transformation like this:
public ListenableFuture<Bar> combinedFooToBar() {
ListenableFuture<Foo> futureFoo = fooService.get();
return Futures.transformAsync(futureFoo, fooToBar);
}
Question: what is the equivalent syntax for these classes and transformation function if we were to convert them into RxJava? Assume that we want to convert FooService and BarService into the appropriate RxJava structures. Assume we want to chain async tasks using the result of calling FooService as the parameter for BarService.
NB: I am just starting to learn about RxJava syntax. When I have finished studying the syntax I will attempt answer the question myself. However, in the meantime if anyone wants to answer they are welcome.
The Guava code translates into RxJava2 code as follows:
FooService.java
public class FooService {
Observable<Foo> getFoo() {
return Observable.fromCallable(new Callable<Foo>() {
#Override
public Foo call() throws Exception {
return new Foo();
}
});
}
}
BarService.java
public class BarService {
Observable<Bar> getBar(final Foo foo) {
return Observable.fromCallable(new Callable<Bar>() {
#Override
public Bar call() throws Exception {
return new Bar(foo);
}
});
}
}
FooBarService.java
public class FooBarService {
private final FooService fooService;
private final BarService barService;
public FooBarService(FooService fooService, BarService barService) {
this.fooService = fooService;
this.barService = barService;
}
Observable<Bar> getFooBar() {
return fooService.getFoo()
.concatMap(new Function<Foo, ObservableSource<? extends Bar>>() {
#Override
public ObservableSource<? extends Bar> apply(#NonNull Foo foo) throws Exception {
return barService.getBar(foo);
}
});
}
}
Hence, concatMap and flatMap are similar to Futures.transformAsync and map is similar to Futures.transform (non-async).
Note also this Github project called Future Converter for conversion between ListenableFuture and Observable.