Uncategorized

Different Ways to Mock Using Mockito in Java

Berief introduction about ‘Mockito” =>

Mockito is a framework which allow to mock the objects and mock objects basically imitate the real world objects and their behavior.

There are several Way to Mock object or method using Mockito.
Let’s jump straight into find out different ways to Mock using Mockito:

First way:

import org.mockito.Mockito;
public class test_hello_world_gets_printed() {
HelloWorld helloWorld = Mockito.mock(HelloWorld.class);
}

Second Way:

import org.mockito.Mockito;
@RunWith(MockitoJunitRunner.class)
public class test_hello_world_gets_printed() {
@Mock HelloWorld helloworld;
//rest of the code
}

Third Way:

import org.mockito.Mockito;
@RunWith(MockitoJunitRunner.class)
public class test_hello_world_gets_printed() {
@InjectMocks HelloWorld helloworld;
@Mock HelloWorldDependency helloWorldDependency; //This mock will inject into the HelloWorld
}

Main different between @Mock and @InjectMock.

@Mock allow you to mock the object. @InjectMock create the instance of the class and allow you to inject the mock which are created using @Mock.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s