Unit Testing with Mockito/PowerMockito

Mockito is an open-source Mocking framework in Java. The features it provides for unit-testing is important.
It has simplified test case writing for developers. While Mockito can help with test case writing, there are certain things it cannot do viz:. mocking or testing private, final or static methods. That is where, PowerMockito comes to the rescue. PowerMockito is capable of testing private, final or static methods as it makes use of Java Reflection API.

The best way to get started with Mockito, or PowerMockito is to find its Maven dependency and add it to the project.

Here are the dependencies we need to add:

Maven Dependencies –

             org.mockito
             mockito-all
              1.9.5
              test
 
 
            org.powermock
            powermock-api-mockito
            1.6.2
            test
 
 
           org.powermock
           powermock-module-junit4
           1.6.2
           test

Annotations

Allows shorthand creation of objects required for testing.

  • Minimizes repetitive mock creation code
  • Makes the test class more readable

Few exmaples –

@RunWith – Indicates which framework APIs to refer to
For PowerMockito – @RunWith(PowerMockRunner.class)

For Mockito –  @RunWith(MockitoJUnitRunner.class )

@PrepareForTest  -Used only in case of PowerMockito. This informs PowerMockito which classes to prepare with Java Reflection API for testing.

@Test – Defines the method as Junit tes case

@Mock – Instead of mocking the object in traditional way. This annotation directly mocks the declared object

@Spy – To Spy on existing instance

@Before– For initialization purpose i.e. initializing the object before use

Generic syntax for mocking –

  1. For mocking the method calls –
    methodPowerMockito.when(object.printMessage(Mockito.anyString())).thenReturn(message);
    Above mocking will return message when printMessage method gets called with any string.
  2. In case of static methods, use like below –
    PowerMockito.mockStatic(PropertiesReader.class); PowerMockito.when(PropertiesReader.getProperty(Constants.PAGE_SIZE)).thenReturn(ONE);

    Here, getProperty(..) is a static method present inside class-  PropertiesReader
    So static mock class before mocking its static method

  3. PowerMockito.whenNew(ClassWithFinalMethods.class).withNoArguments().thenReturn(mockObject);

    This will mock the new object creation
    i.e. when new instance of type –  ClassWithFinalMethods is being generated , our mocked object –  ‘mockObject’ will get returned instead of actual/real new object.

  4. Whitebox.setInternalState(mockVmReplication1, ID_PROPERTY, REPLICATION_ID1);

    This will set the state/value of member variables inside mocked object
    In above example,  ID_PROPERTY of  mockVmReplication1 will get set with value =  REPLICATION_ID1

Call real methods to test using mocked objects –
Real methods can be called from Junit test cases in 2 ways-

  1. Using doCallRealMethod() –
    Mockito.when(mockObject.methodUnderTest().thenCallRealMethod();

    This will call actual method – methodUnderTest() when called using mocked object – mockObject.methodUndertest();

  2. Using actual object creation –
    ClassUnderMock obj = new ClassUnderMock();
    obj.methodUnderTest();
Pros Cons
doCallRealMethod dont create real objects Actual object creation will create real objects which is not recommended in mocking
Real object creation avoids setting of member variables present inside constructor Need to set state of member variables which are getting set in constructor

Assert and Verify –
Assert and Verify are used for checking/verifying the results of mocking.
Assert class has multiple static methods which can be used for testing the results of mocking. Below are the few examples for the same:-
Assert.assertEquals – Fails when expected and actual value are not equal
Assert.assertNotNull – Fails when actual value is NULL
Assert.assertNotEquals – Fails when expected and actual value are equal
Assert.assertTrue – Fails when actual value is false
Assert.assertFalse – Fails when actual value is true

Verify()-

  1. To ensure that the code satisfies all of the required functionality, under all (or most of) the input combinations/values.
  2. To ensure that I can change the implementation, and rely on JUnit test cases to tell me that all my functionality is still satisfied.
Mockito.verify(mockedObject, Mockito.times(1)).methodUnderTest();

This will verify whether the methdUndertest() is called only 1s on mockedObject
If not then execution fails with below trace-
“Wanted 2 times but was 1 time”

[Tweet “Unit Testing with Mockito/PowerMockito ~ via @CalsoftInc”]

Want to know more about open source frameworks like Mockito? 

 
Share:

Related Posts

Technical Documentation

Technical Documentation Review and Tips

Technical reviews are vital for effective and quality documentation. To make this happen, have documentation and its reviews listed as one of the deliverables – just like development or testing. This will place priority on the process, and ensure everyone involved understands the importance of proper and thorough reviews.

Share:
Technology Trends 2024

Technology Trends 2024- The CXO perspective

In the rapidly evolving landscape of 2024, technology trends are reshaping industries and redefining business strategies. From the C-suite perspective, executives are navigating a dynamic environment where artificial intelligence, augmented reality, and blockchain are not just buzzwords but integral components of transformative business models. The Chief Experience Officers (CXOs) are at the forefront, leveraging cutting-edge technologies to enhance customer experiences, streamline operations, and drive innovation. This blog delves into the strategic insights and perspectives of CXOs as they navigate the ever-changing tech terrain, exploring how these leaders are shaping the future of their organizations in the era of 2024’s technological evolution.

Share:
Technology Trends 2024

The Winds of Technology Blowing into 2024

As 2023 draws to a close, the digital landscape is poised for a seismic shift in 2024. Generative Artificial Intelligence (Gen AI) continues its integrative streak, disrupting industries from B2B to healthcare. Networking trends emphasize simplicity, while the synergy of cloud and edge computing with Gen AI promises real-time workflows. Quantum computing, cybersecurity, intelligent automation, and sustainable technology are key players, reshaping the technological fabric. Join us as we navigate the transformative currents of 2024, unraveling the impact on enterprises in our forthcoming article. Stay tuned for the tech evolution ahead!

Share:
Generative AI Shaping Future Industries

[Infoblog] Generative AI Shaping Future Industries

Generative AI is at the forefront of innovation, harnessing the power of machine learning algorithms to create new and original content, from images and music to entire virtual environments. This infographic depicts how Gen AI is evolving industries and shaping its future.

Share:

Enhancing vCenter Capabilities with VMware vCenter Plugins: A Deep Dive

 vCenter Server is one of the most powerful tools in VMware’s product portfolio, enabling efficient management of virtualized environments. One of the most used features in vCenter is the vCenter plugin, which extends the capabilities by providing custom features such as 3rd Party system discovery, and provisioning, providing a unified view, allowing administrators to manage vSphere, and 3rd Party systems seamlessly.

Share:
Generative AI: Transforming Industries for Success

Generative AI : Transforming Industries for Success

Generative AI is the hot topic of discussion everywhere and is being embraced by everyone. Read this blog to explore how different sectors are leveraging Generative AI to drive innovation, enhance efficiency, and deliver superior experiences.

Share: