Thursday, May 9, 2024
HomeJava10 Examples Of Mockito + JUnit in Java for Unit Testing

10 Examples Of Mockito + JUnit in Java for Unit Testing


Hi there guys, if you’re writing unit take a look at in Java then you understand how troublesome it’s to jot down particularly if you’re testing a category which relies upon different class like

and you can not hook up with precise server. At these time, a mocking library like Mockito involves rescue. Given the elevated deal with unit testing and code protection, I’ve discover myself utilizing Mockito increasingly more together with JUnit in final a few years however I have never written many articles on Mockito but however that’s chaging now. On this article, I’m going to share 10 important Mockito examples which I belive each Java programmer ought to know. However, earlier than we get to the ten greatest examples that can train you every thing there’s to find out about Mockito in Java, let me let you know somewhat bit extra about what it truly is.

Mockito is principally an open-source framework that lets you simply create take a look at doubles or mocks. A take a look at double is definitely only a generic time period for a selected case the place you exchange the manufacturing object for testing.

Mockito lets you work with a wide range of take a look at doubles like stubs, spies, and mocks. Stubs are literally just a few objects with a set of predefined return values. Spies are additionally similar to stubs. However they’ll additionally file the stats associated to how they’re executed. 

Mocks are additionally objects with predefined return values to technique executions. It additionally has recorded expectations of the executions.

On this checklist, we now have compiled 10 examples of Mockito in Java. Hold studying to search out out extra.

 

1. Setting Up Mockito In Maven

So as to add Mockito, it is advisable to add the newest Mockito model by Maven. See the next instance

pom.xml

<dependency>

    <groupId>org.mockito</groupId>

    <artifactId>mockito-core</artifactId>

    <model>4.6.1</model>

    <scope>take a look at</scope>

</dependency>

construct.gradle

testCompile group: ‘org.mockito’, identify: ‘mockito-core’, model: ‘4.6.1’

You
may also course of Mockito annotations with the assistance of JUnit 5. However you
might want to use the MockExtension. See the next instance:

@ExtendWith(MockitoExtension.class)

public class ApplicationTest {

   //code

}

In case you might be utilizing the legacy JUnit 4,

@RunWith(MockitoJUnitRunner.class)

public class ApplicationTest {

//code

}

public class ApplicationTest {

@Rule public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

//code

}

2. Annotations Is Mockito

You
can annotate an object utilizing the @Mock annotation. This can even make
the code extra readable and neat. You possibly can specify the mock object identify
which might be helpful in case there are errors or one thing. Try
the next instance:

bundle com.journaldev.mockito.mock;

import java.util.Listing;

import static org.junit.jupiter.api.Assertions.*;

import static org.mockito.Mockito.*;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Take a look at;

import org.mockito.Mock;

import org.mockito.MockitoAnnotations;

public class MockitoMockAnnotationExample {

@Mock

Listing<String> mockList;

@BeforeEach

public void setup() {

//if we do not name beneath, we are going to get NullPointerException

MockitoAnnotations.initMocks(this);

}

@SuppressWarnings(“unchecked”)

@Take a look at

public void take a look at() {

when(mockList.get(0)).thenReturn(“JournalDev”);

assertEquals(“JournalDev”, mockList.get(0));

}

}

3. Creating A Mock In Mockito

You
can use the Mockito class mock() technique for making a mock object of a
sure class or perhaps a interface. It’s also one of many best methods
to create a mock.

bundle com.journaldev.mockito.mock;

import java.util.Listing;

import static org.mockito.Mockito.*;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Take a look at;

public class MockitoMockMethodExample {

@SuppressWarnings(“unchecked”)

@Take a look at

public void take a look at() {

// utilizing Mockito.mock() technique

Listing<String> mockList = mock(Listing.class);

when(mockList.dimension()).thenReturn(5);

assertTrue(mockList.dimension()==5);

}

}

On this instance, you may see that we’re utilizing JUnit 5 for writing take a look at instances together with Mockito to mock the objects.

4. Utilizing Mockito spy() For Partial Mocking

If
you want to mock just some particular behaviours, you may name the
actual strategies for behaviours which can be unstubbed. You possibly can then create a
spy object utilizing the Mockito spy() technique. 

bundle com.journaldev.mockito.mock;

import static org.junit.jupiter.api.Assertions.assertEquals;

import static org.mockito.Mockito.spy;

import static org.mockito.Mockito.when;

import java.util.ArrayList;

import java.util.Listing;

import org.junit.jupiter.api.Take a look at;

public class MockitoSpyMethodExample {

@Take a look at

public void take a look at() {

Listing<String> checklist = new ArrayList<>();

Listing<String> spyOnList = spy(checklist);

when(spyOnList.dimension()).thenReturn(10);

assertEquals(10, spyOnList.dimension());

//calling actual strategies since beneath strategies usually are not stubbed

spyOnList.add(“Pankaj”);

spyOnList.add(“Meghna”);

assertEquals(“Pankaj”, spyOnList.get(0));

assertEquals(“Meghna”, spyOnList.get(1));

}

}

5. The @InjectMocks Annotation

You possibly can see the next instance to grasp how one can inject a mocked object into one other object. 

bundle com.journaldev.mockito.mock;

import java.util.Listing;

import static org.junit.jupiter.api.Assertions.*;

import static org.mockito.Mockito.*;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Take a look at;

import org.mockito.InjectMocks;

import org.mockito.Mock;

import org.mockito.MockitoAnnotations;

public class MockitoInjectMockAnnotationExample {

@Mock

Listing<String> mockList;

//@InjectMock creates an occasion of the category and 

//injects the mocks which can be marked with the annotations @Mock into it.

@InjectMocks

Fruits mockFruits;

@BeforeEach

public void setup() {

//if we do not name beneath, we are going to get NullPointerException

MockitoAnnotations.initMocks(this);

}

@SuppressWarnings(“unchecked”)

@Take a look at

public void take a look at() {

when(mockList.get(0)).thenReturn(“Apple”);

when(mockList.dimension()).thenReturn(1);

assertEquals(“Apple”, mockList.get(0));

assertEquals(1, mockList.dimension());

//mockFruits names is utilizing mockList, beneath asserts verify it

assertEquals(“Apple”, mockFruits.getNames().get(0));

assertEquals(1, mockFruits.getNames().dimension());

mockList.add(1, “Mango”);

//beneath will print null as a result of mockList.get(1) isn’t stubbed

System.out.println(mockList.get(1));

}

}

class Fruits{

non-public Listing<String> names;

public Listing<String> getNames() {

return names;

}

public void setNames(Listing<String> names) {

this.names = names;

}

}

6. The @Spy Annotation

Because the identify suggests, you should use the @Spy annotation for spying on an object. Try the next instance. 

bundle com.journaldev.mockito.mock;

import static org.junit.jupiter.api.Assertions.*;

import static org.mockito.Mockito.*;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Take a look at;

import org.mockito.MockitoAnnotations;

import org.mockito.Spy;

public class MockitoSpyAnnotationExample {

@Spy

Utils mockUtils;

@BeforeEach

public void setup() {

MockitoAnnotations.initMocks(this);

}

@Take a look at

public void take a look at() {

when(mockUtils.course of(1, 1)).thenReturn(5);

//mocked technique

assertEquals(5, mockUtils.course of(1, 1));

//actual technique referred to as since it isn’t stubbed

assertEquals(20, mockUtils.course of(19, 1));

}

}

class Utils{

public int course of(int x, int y) {

System.out.println(“Enter Params = “+x+”,”+y);

return x+y;

}

}

7. ToDoBusinessMock.java Instance

Try the next piece of code to see how you should use ToDoBusinessMock.java:

import static org.junit.Assert.assertEquals;  

import static org.mockito.Mockito.mock;  

import static org.mockito.Mockito.when;  

  

import java.util.Arrays;  

import java.util.Listing;  

import org.junit.Take a look at;  

  

public class ToDoBusinessMock {  

  

    @Take a look at  

    public void testusing_Mocks() {  

          

        ToDoService doService = mock(ToDoService.class);  

           

 
      Listing<String> combinedlist = Arrays.asList(” Use Core Java
“, ” Use Spring Core “, ” Use w3eHibernate “, ” Use Spring MVC “);  

        when(doService.getTodos(“dummy”)).thenReturn(combinedlist);  

          

        ToDoBusiness enterprise = new ToDoBusiness(doService);  

      

        Listing<String> alltd = enterprise.getTodosforHibernate(“dummy”);   

          

        System.out.println(alltd);  

        assertEquals(1, alltd.dimension());  

    }  

 }  

8. Utilizing TestList.java

That is very useful for mocking a listing class.

import static org.junit.Assert.*;  

import static org.mockito.Mockito.when;  

  

import java.util.Listing;  

import org.junit.Take a look at;  

import org.mockito.Mock;  

  

public class TestList {  

  

    @Take a look at  

    public void testList_ReturnsSingle_value() {  

  

        Listing mocklist = mock(Listing.class);  

                           when(mocklist.dimension()).thenReturn(1);  

  

        assertEquals(1, mocklist.dimension());  

        assertEquals(1, mocklist.dimension());  

          

                          System.out.println( mocklist.dimension());  

        System.out.println(mocklist);  

    }  

 }  

10. How To Get A number of Return Values For A Take a look at

You can too mock a listing class with a number of return values. The checklist within the following instance comprises three gadgets.

import static org.junit.Assert.*;  

import static org.mockito.Mockito.when;  

  

import java.util.Listing;  

import org.junit.Take a look at;  

import org.mockito.Mock;  

  

public class TestList {   

      

      @Take a look at   

      public void testList_Returns_MultipleValues() {  

        

      Listing mocklist = mock(Listing.class);  

      when(mocklist.dimension()).thenReturn(1).thenReturn(2).thenReturn(3);  

        

      assertEquals(1, mocklist.dimension());   

      assertEquals(2, mocklist.dimension());  

      assertEquals(3, mocklist.dimension());  

        

      System.out.println(mocklist.dimension());   

      System.out.println(mocklist);  

        

      }  

 }    

Conclusion

For those who favored this checklist of 10 examples of Mockito in Java, be at liberty to share it together with your family and friends. 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments