Here is an existing class and its method I am trying to mock:
public class ClassUndertest{
private Object field_private = new Object();
public Object method_public()
{
field_private.method();
method_private();
}
private Object method_private()
{
....
return Object;
}
}
My tests partially mocks ClassUndertest:
ClassUndertest partialmockinstance = PowerMock.createPartialMock(ClassUndertest.class, "method_private");
When I run mock object:
partialmockinstance.method_public();
field_private is not intialized and so test throws null pointer.
Is there anyway to circumvent this issue?
Fields are initialized when a constructor is invoked. I think the default behaviour of PowerMock is to not invoke any constructor.
With looking at the javadoc I would try the following method instead:
ClassUndertest partialmockinstance = PowerMock.createPartialMockAndInvokeDefaultConstructor(ClassUndertest.class, "method_private");
Related
I have read some post about it but nothing solved my problem. I have a class which is singleton and one method of this class is being called inside another class. I need to mock this method call.
Class SingletonClass
{
public static SingletonClass instance()
{
......
return instance;
}
public boolean methodToBeMocked(Object obj)
{
return false;
}
}
And the another class is :
Class A
{
Object doSomeStuff()
{
......
boolean result = SingletonClass.instance.methodToBeMocked();
}
}
And I am mocking the method methodToBeMocked in my test class. I have tried to use doReturn instead of thenReturn as it is suggested in other posts but it did not help.
My test class is :
Class TestClass{
Class A a = new A();
public void test()
{
SingletonClass singletonClass = mock(SingletonClass.class);
doReturn(true).when(singletonClass).methodToBeMocked(any());
a.doSomeStuff(); // here mocked method returns false
// but if I do this below it returns true !!!!
Object obj = new Object();
boolean result = singletonClass.mockedMethod(obj);
}
}
So why I am not getting true when a.doSomeStuff is called ? What is wrong here ?
For the benefit of others, I was using the following mock with the expectation it would not call someMock.someMethod(), unlike the when(someMock.someMethod()).doReturn("someString") usage.
Mockito.doReturn("someString").when(someMock).someMethod();
I could not understand why the real someMethod() was still being called. It turns out the method was specified as final. Mockito can't mock static or final methods.
The problem is the static method public static SingletonClass instance(). The standard mockito library does not support mocking of static methods. I seen two solutions.
You can rewrite small your code as:
Add new method getSingletonClassInstance() to be mocked in test
Class A {
Object doSomeStuff()
{
......
boolean result = getSingletonClassInstance();
}
SingletonClass getSingletonClassInstance(){
return SingletonClass.instance.methodToBeMocked();
}
}
use spy from mockito library to create an instance of Class A
import static org.mockito.Mockito.spy;
.....
Class TestClass{
public void test()
{
Class A a = spy(new A());
SingletonClass singletonClass = mock(SingletonClass.class);
doReturn(true).when(singletonClass).methodToBeMocked(any());
doReturn(singletonClass).when(a).getSingletonClassInstance();
a.doSomeStuff(); // here mocked method returns false
// but if I do this below it returns true !!!!
Object obj = new Object();
boolean result = singletonClass.mockedMethod(obj);
}
}
More information about the spy in mockito. Spy used real instance and invoke real method but provide a functionality to mock specific method. Don't worry about the others method they will continue to work with real implementation, only mocked method will be affected.
You can use power mockito to mock the public static SingletonClass
instance()
Is there any way to mock objects which are initialized in the method itself. For example
void myMethod(){
SampleClass sample = new SampleClass();
int count = sample.getProductCount(5L);
}
I want to mock getProductCount method something like
when(sample.getProductCount(any(Long.class)).thenReturn(10)
But I don't find a way to do so. Any advice?
I'm using #Spy which lets you mock specific method,
A field annotated with #Spy can be initialized explicitly at declaration point.
In your case prepare the spy:
#Spy
private SampleClass sample = new SampleClass();
#BeforeMethod
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
And in test:
doReturn(10).when(sample).getProductCount(any(Long.class));
public enum SPHttpClient {
;
private static fun(clientInstance) {
HttpPost postRequest;
/* some processing*/
clientInstance.execute(postRequest);
// I need to mock this execute statement
}
}
Writing Junit test on private method fun,
How to invoke private method which is in ENUM type and also I need to mock clientInstance which is passed through argument of private method??
SPHttpClient spHttpClient;
final Method method = spHttpClient.getClass().getDeclaredMethod("fun", HttpClient.class);
method.setAccessible(true);
Object actual = method.invoke(spHttpClient, mockHttpClient);
I think getclass wont work for enums ??
The signature of invoke is invoke(Object obj, Object... args). obj has to be the this-Object. Since your method is static, there is no this object, you may pass null, but you must not omit it, i.e. following works:
final Method method = SpHttpClient.class.getDeclaredMethod("fun", HttpClient.class);
method.setAccessible(true);
Object actual = method.invoke(null, mockHttpClient);
In a class I'm testing, there is a private method that instantiates the GetRequest class in Unirest. How do I use Mockito so that the instantiation of GetRequest class in getResponse() results in a mock object that I use in my JUnit test?
public ClassUnderTest {
public String methodToTest() {
String url = "http://localhost:8080";
String result = getResponse(url);
return result;
}
private String getResponse(String url) {
GetRequest getRequest = new GetRequest(HttpMethod.GET, url);
... = getRequest.header(...).headers(...).asJson();
...etc...
}
}
Thank you,
Rico
One solution is to use a partial mock as in Use Mockito to mock some methods but not others. I can refactor the call to the constructor in a private method and mock that.
I have a method as follows
private void validate(String schemaName){
....
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);**strong text**
Source schemaFile = new SteamSource(getClass().getClassLoader().getResourceAsStream(schemaName));
Schema schema = factory.newSchema(schemaFile);
....
}
This method get called from another method which I need to test(Using easymock and powermock). I'm struggling to mock following line
Source schemaFile = new SteamSource(getClass().getClassLoader().getResourceAsStream(schemaName));
Can someone give me a clue on this?
Current Status
Following is the mock statement
expectNew(StreamSource.class, anyObject(InputStream.class)).andReturn(mockedobject);
Powermock.replay(mockedobject, StreamSrouce.class);
This throws the following exception.
org.powermock.reflect.exceptions.TooManyConstructorsFoundException: Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.
Matching constructors in class javax.xml.transform.stream.StreamSource were:
I think you can do it using powermock in the following way (I'm just following the tutorial here):
Let's say you're class looks like this:
public class MyClass {
private void validate(String schemaName) {
....
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);**strong text**
Source schemaFile = new SteamSource(getClass().getClassLoader().getResourceAsStream(schemaName));
Schema schema = factory.newSchema(schemaFile);
....
}
}
You should create a test class like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
public class MyClassTest {
private MyClass testedClass = new MyClass();
private ClassLoader mockedClassLoader = createMock(ClassLoader.class);
private InputStream mockedInputStream = createMock(InputStream.class);
#Before
public void setUp() {
PowerMock.createPartialMock(MyClass.class, "getClass");
expect(testedClass.getClass()).andReturn(mockedClassLoader);
expected(mockedClassLoader.getResourceAsStream(***You string***)).andReturn(mockedInputStream);
replayAll(); // Not sure if that's the name of the method - you need to call replay on all mocks
}
#Test
public void testValidate() {
// Run your test logic here
}
}
Please excuse me if some of the easymock methods I used are named a bit differently. But this is the basic idea.
I think you need one or a combination of the following. Use Powermock constructor mocking for the new StreamSource as documented here: Powermock MockConstructor. You will probably also need to use a mock for SchemaFactory which mean you will need to mock the static factory method call via Powermock: MockStatic