I am using Mockito/PowerMockito APIs to mock some objects for junit cases.
In the example given below, I want to create a mock object of class C (returned by Utils.getC()). Also I want to use same mock object of C in B.execute(), and not a new object. Is there a way I can achieve this? Please help. [Update - Thanks Lino for answering this. I have edited the code given below.]
However, this works for static methods only. I am not able to mock instance method D.displayMessage() (invoked from A.execute() and B.execute()).
#PrepareForTest(mock.Utils.class)
#RunWith(PowerMockRunner.class)
public class TestMock {
private static C c;
private static D d;
#BeforeClass
public static void runOnceBeforeClass() {
try {
System.out.println("#BeforeClass - runOnceBeforeClass");
PowerMockito.mockStatic(Utils.class);
c = Mockito.mock(C.class);
System.out.println("c = " + c);
PowerMockito.doReturn("Hello!!").when(c).displayMessage();
Answer<Void> answer = new Answer() {
public Void answer(InvocationOnMock invocation) {
System.out.println("I can perform!");
return null;
}
};
PowerMockito.doAnswer(answer).when(c).perform();
PowerMockito.when(Utils.getC()).thenReturn(c);
Answer<Void> answer1 = new Answer() {
public Void answer(InvocationOnMock invocation) {
System.out.println("I can utilize!");
return null;
}
};
PowerMockito.doAnswer(answer1).when(Utils.class);
Utils.utilize();
Answer<Void> answer2 = new Answer() {
public String answer(InvocationOnMock invocation) {
System.out.println("I can run with params!");
return null;
}
};
PowerMockito.doAnswer(answer2).when(Utils.class);
Utils.runWithParams(Mockito.anyString(), Mockito.anyInt(), Mockito.any());
d = PowerMockito.mock(D.class);
PowerMockito.when(d.displayMessage()).thenReturn("D: I can display!");
PowerMockito.whenNew(D.class).withNoArguments().thenReturn(d);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#AfterClass
public static void runOnceAfterClass() {
System.out.println("#AfterClass - runOnceAfterClass");
}
#Before
public void runBeforeTestMethod() {
System.out.println("#After - runBeforeTestMethod");
}
#After
public void runAfterTestMethod() {
System.out.println("#After - runAfterTestMethod");
}
#Test
public void testExecution() {
System.out.println(Utils.getC().displayMessage());
A a = new A();
a.execute();
}
}
class A {
public void execute() {
System.out.println("executing A");
B b = new B();
b.execute();
System.out.println(new D().displayMessage());
}
}
class B {
public void execute() {
System.out.println("executing B");
C c1 = Utils.getC();
System.out.println("c = " + c1.hashCode());
c1.perform();
Utils.utilize();
Utils.runWithParams("", 3, "2");
System.out.println(new D().displayMessage());
}
}
class C {
public String displayMessage() {
return "C: I can't display.";
}
public void perform() {
System.out.println("I can't perform.");
}
}
class D {
public String displayMessage() {
return "D: I can't display.";
}
}
class Utils {
public static C getC() {
return null;
}
public static void utilize() {
System.out.println("I can't unitilize.");
}
public static String runWithParams(String s, Integer i, Object o) {
System.out.println("I can't run with params.");
return "abc";
}
}
If you are trying to reuse the mocked object of C, for the static method call inside execute() method of B , the same mocked object can be reused.
Related
I have this chained method call
Integer.parseInt(A.get().getC().getD().toString());
I need to make this with reflection. I know that I can use Class.forName(String class) and then invoke methods, but how do I save method results so I can call that chain.
Classes:
public class A
{
public static B get() { return new B(); }
}
public class B
{
public C getC() { return new C();}
}
public class C
{
public C getD() { return new D();}
}
Suppose we have this classes:
public class A {
public B getB() { return new B(); }
public static B getBStatic() { return new B(); }
}
public class B { public C getC() { return new C();}}
public class C { public String getD() { return "done"}}
Example 1:
public static void main(String[] args) throws Exception {
Class<A> clazz = A.class;
Constructor<A> constructor = clazz.getConstructor();
A instance = constructor.newInstance();
Method getMethod = clazz.getDeclaredMethod("getB");
Object b = getMethod.invoke(instance);
Method getCMethod = b.getClass().getDeclaredMethod("getC");
Object c = getCMethod.invoke(b);
Method getDMethod = c.getClass().getDeclaredMethod("getD");
String d = (String) getDMethod.invoke(c);
System.out.println(d); // done
}
Example 2:
public static void main(String[] args) throws Exception {
reflection(new A(), "getB", "getC", "getD"); // invoke non static methods
reflection(new A(), "getBStatic", "getC", "getD"); // invoke static and nonstatic methods
reflection(A.getBStatic(), "getC", "getD"); // provide object from static method
reflection(invokeStaticMethod(A.class, "getBStatic"), "getC", "getD"); // invoke static method without instance
}
public static Object invokeStaticMethod(Class<?> clazz, String methodName) throws Exception {
return clazz.getMethod(methodName).invoke(clazz);
}
public static void reflection(Object instance, String... methods) throws Exception {
Object item = instance;
for (String methodName : methods) {
item = item.getClass().getDeclaredMethod(methodName).invoke(item);
}
System.out.println(item); // done
}
I want to be able to pass Object from any class to a specific class. How do i do this? I pass the object in the constructor of the receiving class. One workaround i know is using static variables, but i need the whole object not just the variables.
public class tryitout
{
public static void main(String[] args) {
A a = new A();
B b = new B(a);
b.print();
}
}
class A implements Serializable
{
public int a;
public String b;
A()
{
this.a = 12;
this.b =" nach";
}
}
class B
{
Object obj;
B(Object o)
{
obj = o;
}
void print()
{
System.out.println(obj.a + " "+ obj.b);
}
}
Using Generics :
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class tryitout {
public static void main(String[] args) {
ClassA a = new ClassA("sap",11);
ClassB<ClassA> b = new ClassB<ClassA>(a);
b.print();
}
}
public class ClassA {
private String name;
private int id;
public ClassA(String name, int id) {
super();
this.name = name;
this.id = id;
}
#Override
public String toString() {
return "ClassA [name=" + name + ", id=" + id + "]";
}
}
public class ClassB<T> {
private T genericObj;
public ClassB(T genericObj){
this.genericObj = genericObj;
}
public void print() {
Field nameField = getField("name");
Field idField = getField("id");
try {
System.out.println(nameField.get(genericObj));
System.out.println(idField.getInt(genericObj));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private Field getField(String FieldName) {
Field fld = null;
try {
fld = genericObj.getClass().getDeclaredField(FieldName);
if(Modifier.isPrivate(fld.getModifiers())) {
fld.setAccessible(true);//To get access over private fields
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return fld;
}
}
using generics you can access method also.
I don't know your exact purpose,otherwise other classes can extend any particular Abstract class and you can use that Abstract class as a type inside classB.
public class TypeClass {
protected String name;
protected int id;
protected void paint(){
System.out.println("name: " + name + " | id: " + id);
}
}
public class ClassC extends TypeClass{
public ClassC(String name, int id) {
super();
this.name = name;
this.id = id;
}
#Override
public String toString() {
return "ClassA [name=" + name + ", id=" + id + "]";
}
}
package javaConcept.generics;
public class ClassD {
private TypeClass typeClass;
public ClassD(TypeClass typeClass) {
this.typeClass = typeClass;
}
public void newPaint() {
typeClass.paint();
}
}
public class TempoClass {
public static void main(String[] args) {
ClassC c = new ClassC("sap",11);
ClassD b = new ClassD(c);
b.newPaint();
}
}
maybe use static blocks and anonymous blocks some thing like this
public class HelloWorld{
public static void main(String []args){
B ob1= new B();
C ob2= new C(B.ob);
D ob3= new D();
C ob4= new C(ob3.ob);
}
}
class A
{
//this is empty class just for sake of object to be created
public void imWorking()
{
System.out.println("test");
}
}
class B
{
public static A ob;
static{ob=new A();}//static called once class gets loaded
}
class C
{
public C(){}//Default constructor
public C(A a){a.imWorking();}
}
class D
{
public A ob;
{ob=new A();}//ananomous block calls everytime a new object is created
}
more info Static Initialization Blocks blocks & anonymous blocks][1]
I have some generated code (i.e. it cannot be changed) that looks something like this.
class Generated1 {
public String getA() {
return "1";
}
public void setB(String b) {
}
public void setC(String c) {
}
public void setD(String d) {
}
}
class Generated2 {
public String getA() {
return "2";
}
public void setB(String b) {
}
public void setC(String c) {
}
public void setD(String d) {
}
}
I am exploring these objects by reflection. None of them implement any common interface but there's many of them and I want to treat them as if they implement:
interface CommonInterface {
String getA();
void setB(String b);
void setC(String c);
void setD(String d);
}
It certainly should be possible. This is considered perfectly good code
class CommonInterface1 extends Generated1 implements CommonInterface {
// These are perfectly good classes.
}
class CommonInterface2 extends Generated2 implements CommonInterface {
// These are perfectly good classes.
}
I suppose what I'm looking for is something like:
private void doCommon(CommonInterface c) {
String a = c.getA();
c.setB(a);
c.setC(a);
c.setD(a);
}
private void test() {
// Simulate getting by reflection.
List<Object> objects = Arrays.asList(new Generated1(), new Generated2());
for (Object object : objects) {
// What is the simplest way to call `doCommon` with object here?
doCommon(object);
}
}
My question: How do I treat an object that doesn't implement an interface but actually has all the code to do so as if it does implement the interface.
I want to replace
private void doCommon(Generated1 c) {
String a = c.getA();
c.setB(a);
c.setC(a);
c.setD(a);
}
private void doCommon(Generated2 c) {
String a = c.getA();
c.setB(a);
c.setC(a);
c.setD(a);
}
...
with
private void doCommon(CommonInterface c) {
String a = c.getA();
c.setB(a);
c.setC(a);
c.setD(a);
}
I know I can use a Proxy like this but I'd really prefer to use something better.
private void test() {
// Simulate getting by reflection.
List<Object> objects = Arrays.asList(new Generated1(), new Generated2());
for (Object object : objects) {
// What is the simplest way to call `doCommon` with object here?
doCommon(adapt(object));
}
}
private CommonInterface adapt(Object o) {
return adapt(o, CommonInterface.class);
}
public static <T> T adapt(final Object adaptee,
final Class<T>... interfaceToImplement) {
return (T) Proxy.newProxyInstance(
adaptee.getClass().getClassLoader(),
interfaceToImplement,
// Call the equivalent method from the adaptee.
(proxy, method, args) -> adaptee.getClass()
.getMethod(method.getName(), method.getParameterTypes())
.invoke(adaptee, args));
}
If you're using reflection, you don't need the two CommonInterfaceX classes, you can use a proxy implementing CommonInterface:
public class Wrapper implements InvocationHandler {
private final Object delegate;
public static <T> T wrap(Object obj, Class<T> intf) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Object proxy = Proxy.newProxyInstance(cl, new Class<?>[] {intf},
new Wrapper(obj));
return intf.cast(proxy);
}
private Wrapper(Object delegate) {
this.delegate = delegate;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Method dmethod = delegate.getClass().getMethod(
method.getName(), method.getParameterTypes());
return dmethod.invoke(delegate, args);
}
}
You can use this class as follows:
List<Object> objects = Arrays.asList(new Generated1(), new Generated2());
for (Object object : objects) {
CommonInterface proxy = Wrapper.wrap(object, CommonInterface.class);
doCommon(proxy);
}
UPDATE: note that the same Wrapper class works with any interface.
There's no way to achieve a static type relationship between Generated1 and Generated2.
Even if you created CommonInterface1 and CommonInterface2, you still wouldn't be able to statically use a Generated1 object as a CommonInterface1 because new Generated1() is not a CommonInterface1 (and will never become one)
By far the simplest solution is to change your code generation to add the CommonInterface to Generated1 and Generated2.
If that's absolutely impossible, the only other way to avoid this code duplication is to go for reflection.
You can do it manuallly by reflection.
public class Generated {
public String getA() {
return "A";
}
public String sayHello(String name) {
return "hello " + name;
}
}
public class Helper {
private static final String METHOD_NAME = "getA";
private static final String METHOD_WITH_PARAM_NAME = "sayHello";
public static void main(String[] args) throws Exception {
Generated generated = new Generated();
accessMethod(generated);
accessMethodWithParameter(generated);
}
private static void accessMethod(Generated g) throws Exception {
Method[] methods = g.getClass().getDeclaredMethods();
for(Method method : methods) {
if(isCommonMethod(method)) {
String result = (String) method.invoke(g);
System.out.println(METHOD_NAME + "() = " + result);
}
}
}
private static boolean isCommonMethod(Method m) {
return m.getName().equals(METHOD_NAME) && m.getReturnType().equals(String.class);
}
private static void accessMethodWithParameter(Generated g) throws Exception {
Method[] methods = g.getClass().getDeclaredMethods();
for(Method method : methods) {
if(isCommonMethodWithParameter(method)) {
String result = (String) method.invoke(g, "Max");
System.out.println(METHOD_WITH_PARAM_NAME + "(\"Max\") = " + result);
}
}
}
private static boolean isCommonMethodWithParameter(Method m) {
return m.getName().equals(METHOD_WITH_PARAM_NAME) &&
m.getReturnType().equals(String.class) &&
m.getParameterTypes().length == 1 &&
m.getParameterTypes()[0].equals(String.class);
}
}
Output is
getA() = A
sayHello("Max") = hello Max
If you want to replace as your comment. I think you can do it easily
First, you create interface CommonInterface
interface CommonInterface {
String getA();
void setB(String b);
void setC(String c);
void setD(String d);
}
After that, you create 2 class Generated1 and Generated2 inherited CommonInterface
class Generated1 implements CommonInterface {
#overide
public String getA() {
return "1";
}
#overide
public void setB(String b) {
}
#overide
public void setC(String c) {
}
#overide
public void setD(String d) {
}
}
class Generated2 implements CommonInterface {
#overide
public String getA() {
return "2";
}
#overide
public void setB(String b) {
}
#overide
public void setC(String c) {
}
#overide
public void setD(String d) {
}
}
Hi I have implemented my code like below two snippets but still I am not able to achieve synchronization in threads, as my methods are synchronized still no thread is waiting for other till complete. can you please let me know what mistake did I make in below snippet?
but when I put sleep on Thread in between then it works fine but that is not better way to implement by putting sleep on Thread
Option 1:
public class A{
public static void main(String args[]){
C c = new C();
ExecutorService executorService = Executors.newFixedThreadPool(10);
B t1 = new B(c);
for(int i = 1; i <=10; i++) {
executorService.submit(/*new B(c)*/t1);
}
executorService.shutdown();
try{
executorService.awaitTermination(Long.MAX_VALUE,TimeUnit.NANOSECONDS);
}catch(InterruptedException e){
System.out.println("Error while checking tread life: "+e);
}
}
}
public class B extends Thread{
C c;
static final Object lockObject = new Object();
public B(C c) {
this.c = c;
}
public void run(){
someProcess();
}
synchronized public void someProcess(){
String something = c.C();
if(something == null || "".equalsIgnoreCase(something)){
c.A();
}else{
c.B();
}
}
}
public class C {
synchronized public void method A(){
//insert the recods
}
synchronized public void method B(){
//update the records
}
synchronized public String method C(){
// searching a record to get it's id if it exist
return something;
}
}
Option 2:
public class A {
public static void main(String args[]) {
C c = new C();
ExecutorService executorService = Executors.newFixedThreadPool(10);
B t1 = new B(c);
for(int i = 1; i <=10; i++) {
executorService.submit(/*new B(c)*/t1);
}
if(executorService !=null) {
executorService.shutdown();
try {
executorService.awaitTermination (Long.MAX_VALUE,TimeUnit.NANOSECONDS);
}catch(InterruptedException e) {
System.out.println("Error while checking tread life: "+e);
}
}
}
}
public class B extends Thread {
C c;
static final Object lockObject = new Object();
public B(C c) {
this.c = c;
}
public void run() {
someProcess();
}
public void someProcess() {
synchronized(this) {
String something = c.C();
if(something == null || "".equalsIgnoreCase(something)) {
c.A();
}else{
c.B();
}
}
}
}
public class C {
synchronized public void method A() {
//insert the recods
}
synchronized public void method B() {
//update the records
}
synchronized public String method C() {
// searching a record to get it's id if it exist
return something;
}
}
Option 3:
public class A {
public static void main(String args[]) {
C c = new C();
ExecutorService executorService = Executors.newFixedThreadPool(10);
B t1 = new B(c);
for(int i = 1; i <=10; i++) {
executorService.submit(/*new B(c)*/t1);
}
if(executorService !=null) {
executorService.shutdown();
try {
executorService.awaitTermination (Long.MAX_VALUE,TimeUnit.NANOSECONDS);
}catch(InterruptedException e) {
System.out.println("Error while checking tread life: "+e);
}
}
}
}
public class B extends Thread {
C c;
static final Object lockObject = new Object();
public B(C c) {
this.c = c;
}
public void run() {
someProcess();
}
public void someProcess() {
synchronized(this) {
String something = c.C();
if(something == null || "".equalsIgnoreCase(something)) {
c.A();
}else{
c.B();
}
}
}
}
public class C {
public void method A() {
synchronized(this) {
//insert the recods
}
}
public void method B() {
synchronized(this) {
//update the records
}
}
public String method C() {
synchronized(this) {
// searching a record to get it's id if it exist
return something;
}
}
}
Option 4:
public class A {
public static void main(String args[]) {
C c = new C();
ExecutorService executorService = Executors.newFixedThreadPool(10);
B t1 = new B(c);
for(int i = 1; i <=10; i++) {
executorService.submit(/*new B(c)*/t1);
}
if(executorService !=null) {
executorService.shutdown();
try {
executorService.awaitTermination (Long.MAX_VALUE,TimeUnit.NANOSECONDS);
}catch(InterruptedException e) {
System.out.println("Error while checking tread life: "+e);
}
}
}
}
public class B extends Thread {
C c;
static final Object lockObject = new Object();
public B(C c) {
this.c = c;
}
public void run() {
someProcess();
}
public void someProcess() {
synchronized(lockObject) {
String something = c.C(lockObject);
if(something == null || "".equalsIgnoreCase(something)) {
c.A(lockObject);
}else{
c.B(lockObject);
}
}
}
}
public class C {
public void method A(Object lockObject) {
synchronized(lockObject) {
//insert the recods
}
}
public void method B(Object lockObject) {
synchronized(lockObject) {
//update the records
}
}
public String method C(Object lockObject) {
synchronized(lockObject) {
// searching a record to get it's id if it exist
return something;
}
}
}
What is delegation in Java? Can anyone give me a proper example?
That's delegation - exactly like in the real world:
public interface Worker() {
public Result work();
}
public class Secretary() implements Worker {
public Result work() {
Result myResult = new Result();
return myResult;
}
}
public class Boss() implements Worker {
private Secretary secretary;
public Result work() {
if (secretary == null) {
// no secretary - nothing get's done
return null;
}
return secretary.work();
}
public void setSecretary(Secretary secretary) {
this.secretary = secretary;
}
}
(Added Worker interface to get closer to the Delegator pattern)
If you're referring to the delegation pattern, wikipedia has a great example, written in java.
I believe the longer example of the page above is the best one:
interface I {
void f();
void g();
}
class A implements I {
public void f() { System.out.println("A: doing f()"); }
public void g() { System.out.println("A: doing g()"); }
}
class B implements I {
public void f() { System.out.println("B: doing f()"); }
public void g() { System.out.println("B: doing g()"); }
}
class C implements I {
// delegation
I i = new A();
public void f() { i.f(); }
public void g() { i.g(); }
// normal attributes
void toA() { i = new A(); }
void toB() { i = new B(); }
}
public class Main {
public static void main(String[] args) {
C c = new C();
c.f(); // output: A: doing f()
c.g(); // output: A: doing g()
c.toB();
c.f(); // output: B: doing f()
c.g(); // output: B: doing g()
}
}
Same example as aioobe but changed the class names to more intuitive ones. Deriving analogy to real world examples.
public static void main(String[] args) {
Boss boss = new Boss();
boss.toDeveloper();
boss.f();
boss.g();
boss.toSrDeveloper();
boss.f();
boss.g();
}
interface I {
void f();
void g();
}
class Developer implements I {
public void f() {
System.out.println("Developer: f() is too hard for me.");
}
public void g() {
System.out.println("Developer: g() is not in my domain.");
}
}
class SrDeveloper implements I {
public void f() {
System.out.println("Sr. Developer: Okay, I'll see f()");
}
public void g() {
System.out.println("Sr. Developer: I'll do g() too.");
}
}
class Boss implements I {
// delegation
I i;
public void f() {
i.f();
}
public void g() {
i.g();
}
void toDeveloper() {
i = new Developer();
}
void toSrDeveloper() {
i = new SrDeveloper();
}
}
Here is a simple example of how Delegation is used:
interface IDogBehaviour {
public void doThis();
}
class BarkSound implements IDogBehaviour {
public void doThis() {
System.out.println("Bark!");
}
}
class WagTail implements IDogBehaviour {
public void doThis() {
System.out.println("Wag your Tail!");
}
}
class Dog {
private IDogBehaviour sound = new BarkSound();
public void doThis() {
this.sound.doThis();
}
public void setNewBehaviour( IDogBehaviour newDo ){
this.sound = newDo;
}
}
class DelegationDemo {
public static void main( String args[] ){
Dog d = new Dog();
//delegation
d.doThis();
//change to a new behaviour type - wag tail
IDogBehaviour wag = new WagTail();
d.setNewBehaviour( wag );
//Delegation
d.doThis();
}
}