0

Hi my class looks like this.

public class Class1 { public void method1(Object obj) { // Class 2 makes the restApiCall and result as "SUCCESS" if the HTTP response is 202 Class2 class2 = new Class2(); String result = class2.callRestService(); System.out.println(result); } } 
public class Class2 { public String callRestService() { String url = fetchUrl(System.getProperty(COnstants.URL); String result = callRestServiceAPi(url); // Calling the RestApimethod. return result; } } 

I want to write unit test for the class1 and I want to do it by actually not calling RestAPi means I want to mock class2.callRestService() method to return as "success" or "failure". How can it be done.

1 Answer 1

1

If you use new (and then don't use injection) you'll have always some trouble with test.

You have two alternatives:

  1. Use PowerMockito
  2. Wrap new in a method and mock the method
public class Class1 { protected Class2 getClient(){ return new Class2(); } public void method1(Object obj) { // Class 2 makes the restApiCall and result as "SUCCESS" if the HTTP response is 202 Class2 class2 = new Class2(); String result = class2.callRestService(); System.out.println(result); } } 

and then, in your Junit

@Test public void test(){ Class1 class1 = Mockito.spy(new Class1()); Class2 class2 = Mockito.mock(Class2.class); Mockito.doReturn("your result").when(class2).callRestService(); Mockito.doReturn(class2).when(class1).getClient(); // assert something } 

More on Mockito here

Sign up to request clarification or add additional context in comments.

2 Comments

Is it not possible without adding that extra method
As I wrote you can use PowerMockito but this is never a good idea, but just last chance

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.