I have a class as :
public class SomeClass {
private String someField;
public SomeClass(String field) {
someField = field;
}
public String getUrl() {
return "http://" + someField;
}
public static class Builder {
private String uri;
public Builder(String url) {
this.uri = url;
}
public SomeClass build() {
return new SomeClass(uri);
}
}
}
The above class is being called from another class as:
class MainClass {
private SomeClass someClass;
public boolean isUrlAvailable() {
someClass = new SomeClass.Builder("myURI").build();
String url = someClass.getUrl();
if (url != null && url.length() > 10) {
return true;
}
return false;
}
}
My requirement is to test the MainClass, for which I need to mock SomeClass and SomeClass.Builder class. I tried to mock the two classes but could not successfully achieve the requirement.
The code you are showing should not require you to mock anything. It only uses that builder to build something. Assuming that you have tested SomeClass/Builder on its own - you just verify that method in Main gives the correct result.
Anyway: mocking a static class is possible - see here. The only thing to pay attention of: to get all the pre-conditions right, for example to have the required annotations:
RunWith(PowerMockRunner.class)
@PrepareForTest(SomeClassBuilderClass.class)
Beyond that: you don't to mock anything static in the first place. Your only problem is the call to new!
And - the real answer here: simply pass in that instance of SomeClass to work in (instead of calling new Builder
inside of the method under test)!