How to use JMockit MockUp for default interface method - jmockit

Trying to apply a MockUp on a Java 8 default interface method, and JMockit tells me that method cannot be found. This has been tried with JMockit 1.15, 1.19, and 1.25. Here's a very simple use case:
#RunWith(JMockit.class)
public class TestTest {
public interface MyInterface {
default void foo(int f) {
bar(String.valueOf(f));
}
void bar(String s);
}
public class MyClass implements MyInterface {
public void bar(String s) {
System.out.println(s);
}
}
#Test
public void testtest() throws Exception {
new MockUp<MyClass>() {
#Mock
void foo(int i) {
System.out.println("MOCKMOCK " + (i*2));
}
#Mock
void bar(String s) {
System.out.println("MOCK " + s);
}
};
MyClass baz = new MyClass();
baz.foo(5);
baz.bar("Hello world");
}
}
This gets me the error
java.lang.IllegalArgumentException: Matching real methods not found for the following mocks:
com.example.dcsohl.TestTest$1#foo(int)
at com.example.dcsohl.TestTest$1.<init>(TestTest.java:29)
at com.example.dcsohl.TestTest.testtest(TestTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
How can we #Mock this method?

Slightly modifying your use case to return strings instead of printing to standard out the following solution will work.
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mockit.Expectations;
public class TestTest {
public interface MyInterface {
default String foo(int f) {
return bar(String.valueOf(f));
}
String bar(String s);
}
public class MyClass implements MyInterface {
public String bar(String s) {
return s;
}
}
#Test
public void testtest() throws Exception {
MyClass baz = new MyClass();
new Expectations(MyClass.class) {{
baz.foo(anyInt); result = "FOOMOCK";
baz.bar(anyString); result = "BARMOCK";
}};
assertEquals(baz.foo(5), "FOOMOCK");
assertEquals(baz.bar("Hello world"), "BARMOCK");
}
}
There are many useful examples of how to mock out interfaces with method bodies (ie default or static methods) outlined in the examples section on the jmockit github repository.

Use #Mocked instead of a MockUp, it supports default methods.

Related

Is this considered as good approach of using interface type in class

Say i have a code as follows
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
class ClassWithInterfaces : Interface1,Interface2
{
void method1(){}
void method2(){}
}
Now in my "manager" class i implement this as follows :
public OtherClass
{
Interface1 interface1;
Interface2 interface2;
public void someMethod()
{
ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
interface1 = classWithInterfaces;
interface2 = classWithInterfaces
}
}
I don't feel that this is the right way to do it hovewer i can't come up with other solutions i can't use Dependency Injection Frameworks in my project if you ask about that. Can you tell me wheter apart from DI there is a better way of doing that?
Hello and welcome to Stack Overflow :-)
You don't have to use a framework in order to do DI. In fact, there are some languages that make it impossible to use a framework for DI - e.g., C++.
Any way, in your case, the proper way to do DI is like this:
interface Interface1
{
void method1();
}
interface Interface2
{
void method2();
}
interface Interface3 : Interface1, Interface2
{
void method1();
void method2();
}
class ClassWithInterfaces : Interface3
{
void method1(){}
void method2(){}
}
public OtherClass
{
Interface3 m_interface3;
OtherClass(Interface3 interface3)
{
m_interface3 = interface3;
}
public void someMethod()
{
m_interface3.method1();
m_interface3.method2();
}
}
// And now the usage:
public main()
{
ClassWithInterfaces classWithInterfaces = new ClassWithInterfaces();
OtherClass otherClass = new OtherClass(classWithInterfaces);
}

How to send multiple types of classes into Spring stream source

I upgraded my spring stream from 1.3.0 to 2.1.2 and the default serializer was changed from Kyro (deprecated) into Jackson.
I have a kafka topic that more than one type of messages can be sent to. With Kyro I used to deserialize it into Object.class and then cast it to the relevant type of class.
With jackson I can't achieve this functionality, because I have to specify the type of class I want to deserialize to in advance, otherwise, it's been deserialized into a string.
I tried to find an example but couldn't find anything. Any ideas how can I achieve the same functionality? I want to make it as efficient as possible.
You can add hints to the Jackson encoding so it is decoded to the right concrete type:
#JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="#class")
#SpringBootApplication
#EnableBinding(Processor.class)
public class So56753956Application {
public static void main(String[] args) {
SpringApplication.run(So56753956Application.class, args);
}
#StreamListener(Processor.INPUT)
public void listen(Foo foo) {
System.out.println(foo);
}
#Bean
public ApplicationRunner runner(MessageChannel output) {
return args -> {
output.send(new GenericMessage<>(new Bar("fiz")));
output.send(new GenericMessage<>(new Baz("buz")));
};
}
#JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="#class")
public static abstract class Foo {
private String bar;
public Foo() {
super();
}
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
#Override
public String toString() {
return getClass().getName() + " [bar=" + this.bar + "]";
}
}
public static class Bar extends Foo {
public Bar() {
super();
}
public Bar(String bar) {
super(bar);
}
}
public static class Baz extends Foo {
public Baz() {
super();
}
public Baz(String bar) {
super(bar);
}
}
}
and
com.example.So56753956Application$Bar [bar=fiz]
com.example.So56753956Application$Baz [bar=buz]
See here.
You can still use Kryo if you want. You can just add it manually using #StreamMessageConverter- https://cloud.spring.io/spring-cloud-stream/spring-cloud-stream.html#spring-cloud-stream-overview-user-defined-message-converters.
With regard to "With jackson I can't achieve this functionality, because I have to specify the type of class. . ." - that is not accurate since the type of the class gets picked up from the signature of the handler method and it is transparent to you as a user.

Mockito mock with constructor parameter

I am using mockito 1.9.5 and wanting to test a class that i have posted on github.
The issue is that I need to mock the getStringFromExternalSources method.
MyClass code:
public class MyClass {
String a,b,c;
public MyClass(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
public String executeLogic (String d) {
return a + b + c + d;
}
public String getStringFromExternalSources (){
return "i got it from some place else";
}
}
My current test:
#RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
#Test
public void MyClassTest() {
MyClass mc = Mockito.spy(new MyClass("a","b","c") );
Mockito.doReturn("mock").when(mc.executeLogic("real"));
Mockito.doReturn("externalString").when(mc.getStringFromExternalSources());
System.out.println(mc.executeLogic("real"));
}
}
Any pointers ?
You can mock any method using when().thenReturn() construct.
Example:
MyClass mc = Mockito.spy(new MyClass("a","b","c"));
when(mc.getStringFromExternalSource()).thenReturn("I got it from there!!");
So whenever the method 'getStringFromExternalSource()' is invoked for the mocked object mc then it will return "I got it from there!!".
if you want to Test class with different parameters then you can use #Parameters annotation to provide parameters to the class in conjunction with Parameterized runner and mention the parameters in a public static method with #Paramters annotation. A rough example would be:
#RunWith(Parameterized.class)
class SomeTestClass{
#Mock
SomeTestClass mSomeTestClassInstance;
#Parameters
public static Object provideParameters() {
Object[] objects = new Object[]{
0,
0,
2
};
return objects;
}
public SomeTestClass(Object argument1){
mArgument1 = argument1;
}
#Test
public void testSomeMethod{
Object returnValue = mSomeTestClassInstance.testSomeMethod(mArgument1);
assertequals(mArgument1,returnValue)
}
}
How to mock getStringFromExternalSources method:
public class MyClassTest {
#Test
public void MyClassTest() {
MyClass mc = mock(MyClass.class);
when(mc.executeLogic("real").thenReturn("mock");
when(mc.getStringFromExternalSources().thenReturn("externalString");
System.out.println(mc.executeLogic("real"));
}
}

How do I override Class<?>.getName() for certain classes?

My goal is to be able to override what I get back from CustomClass.class.getName() and CustomClass.getClass().getName()
It should return a custom value, which I think is best to define in an attribute like
#NameOverride("Custom.fully.qualified.class.name")
public class CustomClass {}
Is there any way to do that?
Fred's answer is okay, but his aspect could be somewhat more elegant with less code and especially fewer reflection calls. Sorry, I prefer AspectJ native code style, but #AspectJ annotation style would not be much longer:
String around(Class clazz) : call(public String Class.getName()) && target(clazz) {
NameOverride nameOverride = (NameOverride) clazz.getAnnotation(NameOverride.class);
return nameOverride == null ? proceed(clazz) : nameOverride.value();
}
Here is the full source code. I added a class without annotation to show the different behaviour and also a restriction to class definitions - #Target(ElementType.TYPE) - to the annotation class. I am also showing package names and imports:
package test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface NameOverride {
String value();
}
package test;
public class NormalClass {}
package test;
#NameOverride("Custom.fully.qualified.class.name")
public class CustomClass {}
package test;
public class Main {
public static void main(String[] args) {
System.out.println(NormalClass.class.getName());
System.out.println(CustomClass.class.getName());
System.out.println(new NormalClass().getClass().getName());
System.out.println(new CustomClass().getClass().getName());
}
}
package aspectj;
import test.NameOverride;
public aspect GetNameOverrider {
#SuppressWarnings({ "unchecked", "rawtypes" })
String around(Class clazz) : call(public String Class.getName()) && target(clazz) {
NameOverride nameOverride = (NameOverride) clazz.getAnnotation(NameOverride.class);
return nameOverride == null ? proceed(clazz) : nameOverride.value();
}
}
The output:
test.NormalClass
Custom.fully.qualified.class.name
test.NormalClass
Custom.fully.qualified.class.name
This is for sure not the best/fastest solution but maybe a POC...
First of all the file structure:
./src/aspectj:
GetNameOverrider.aj
./src/test:
CustomClass.java Main.java NameOverride.java
NameOverride.java:
#Retention(RetentionPolicy.RUNTIME)
public #interface NameOverride {
String value();
}
GetNameOverrider.aj:
#Aspect
public class GetNameOverrider {
#Around("call(String getName()) && !within(aspectj..*)")
public String advice(ProceedingJoinPoint pjp) throws Throwable {
String ret = (String) pjp.proceed();
String className = "" + pjp.getTarget();
className = className.replace("class ", "");
try {
test.NameOverride anno = Class.forName(className).getAnnotation(
test.NameOverride.class);
if (anno != null) {
return anno.value();
}
} catch (ClassNotFoundException e) {
return ret;
}
return ret;
}
}
gives me for Main.java:
public class Main {
public static void main(String[] args) {
System.out.println(CustomClass.class.getName());
System.out.println(new CustomClass().getClass().getName());
}
}
the output:
Custom.fully.qualified.class.name
Custom.fully.qualified.class.name

proguard copying methods in interface

after decompiling my interface i found out that proguard duplicated my implemented method in the upper level interface that is somehow a class on its own right.
here's how my interface looks like after obfuscation (note that proguard even added the annotation from the implementation)
package com.company.project.f.a.a;
import java.util.List;
import org.apache.log4j.Logger;
#Component(value="ServiceImpl")
public class a
{
public b a(int i)
{
if((i = b.a(i)) != null)
{
if(i.size() == 0)
{
a_.fatal("It is expected at least one record.");
return null;
} else
{
return (b)i.get(0);
}
} else
{
return null;
}
}
public a()
{
a_ = Logger.getLogger(getClass());
}
public com.company.project.b.a.a a()
{
return b;
}
public void a(com.company.project.b.a.a a1)
{
b = a1;
}
private com.company.project.b.a.a b;
Logger a_;
}
same issue happened with the class below (proguard transforming the interface into a class with the same component name)
#Component("testDao")
public class TestDaoImpl implements TestDao {
#Override
public void testing() {
// TODO Auto-generated method stub
}
solved it :
according to mr eric lafortune , the optimizer is merging interface and class .
so i used
-dontoptimize