Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to mock creation of a object inside a constructor of the class to be tested

I am trying to test a class which is creating a new object inside the constructor. I am using PowerMock with Mockito.

public ClassNeedToTest() throws Exception {

    String targetCategory = "somevalue";
    String targetService = "somevalue";
    invoker = new ServiceInvoker(targetCategory, targetService); // throws Exception
}

For the above given code, I am trying to create a instance of ClassNeedToTest to test different method of that class. I am not able to create the object because ServiceInvoker creation is throwing an Exception. The ServiceInvoker class is a third party class. Is there any way to mock ServiceInvoker so that when test class is trying to create ClassNeedToTest I can get the mocking object of ServiceInvoker instead of really calling constructor of ServiceInvoker.

In my test class is am just creating a new instance of ClassNeedToTest:

ClassNeedToTest obj = new ClassNeedToTest();
like image 519
Varun Avatar asked Mar 06 '14 06:03

Varun


People also ask

Can you mock a constructor?

0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes. Similar to mocking static method calls with Mockito, we can define the scope of when to return a mock from a Java constructor for a particular Java class.

Is it possible to create a mock by calling one of its constructor True or false?

You can, but you probably don't want to: ComplexConstructor partialMock = Mockito. mock(ComplexConstructor. class, CALLS_REAL_METHODS);

How do you call a mock method in a constructor?

Faking static methods called in a constructor is possible like any other call. if your constructor is calling a method of its own class, you can fake the call using this API: // Create a mock for class MyClass (Foo is the method called in the constructor) Mock mock = MockManager. Mock<MyClass>(Constructor.

Can we mock the object of class?

We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.


1 Answers

I found the answer for the same. If you follow the steps given below properly, you can mock the objects.

Step 1. - Add annotation to prepare the test class.

@PrepareForTest({ ServiceInvoker.class, ClassNeedToTest.class})

Step 2. - Mock the class.

serviceInvokerMck = Mockito.mock(ServiceInvoker.class);

Step 3. Use the below method to mock the object when new operator is called

PowerMockito.whenNew(ServiceInvoker.class).withAnyArguments().thenReturn(serviceInvokerMck);

What I was not doing was adding the class ClassNeedToTest in PrepareForTest annotation thinking that the only class need to be mocked should be added there.

like image 70
Varun Avatar answered Oct 04 '22 18:10

Varun