Posted on: December 23, 2021 Posted by: rahulgite Comments: 11

Class to test Junit

package com.unittest.unittesting.business;

import com.unittest.unittesting.data.DataService;

public class BusinessImpl {
    private DataService service;

    public DataService getService() {
        return service;
    }

    public void setService(DataService service) {
        this.service = service;
    }

    public int calculateSum(int data[]){
        int sum=0;
        for(int i:data){
            sum+=i;
        }
        return sum;
    }

    public int calculateSumByService(){
        int data[]=service.retriveData();
        int sum=0;
        for(int i:data){
            sum+=i;
        }
        return sum;
    }
}

Basic Junit Test

package com.unittest.unittesting.business;

import com.unittest.unittesting.data.DataService;
import org.junit.jupiter.api.Test;

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

class BusinessImplTest {
    @Test
    void calculateSum() {
        BusinessImpl business=new BusinessImpl();
        int actualResult=business.calculateSum(new int[] {1,2,3});
        int expectedResult= 6;
        assertEquals(expectedResult,actualResult);

    }

    @Test
    void calculateSum_empty() {
        BusinessImpl business=new BusinessImpl();
        int actualResult=business.calculateSum(new int[] {});
        int expectedResult= 0;
        assertEquals(expectedResult,actualResult);

    }
}

Junit with Stubs

package com.unittest.unittesting.business;

import com.unittest.unittesting.data.DataService;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
class someDS implements DataService{

    @Override
    public int[] retriveData() {
        return new int[] {1,2,3};
    }
}
class someDSEmpty implements DataService{

    @Override
    public int[] retriveData() {
        return new int[] {};
    }
}

class BusinessImplStubTest {
    @Test
    void calculateSumByService() {
        BusinessImpl business = new BusinessImpl();
        business.setService(new someDS());
        int actualResult = business.calculateSumByService();
        int expectedResult = 6;
        assertEquals(expectedResult, actualResult);

    }

    @Test
    void calculateSumByService_empty() {
        BusinessImpl business = new BusinessImpl();
        business.setService(new someDSEmpty());
        int actualResult = business.calculateSumByService();
        int expectedResult = 0;
        assertEquals(expectedResult, actualResult);

    }
}

Junit using Mockito

package com.unittest.unittesting.business;

import com.unittest.unittesting.data.DataService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class BusinessImplMockTest {
    BusinessImpl business = new BusinessImpl();
    DataService service= mock(DataService.class);
    @BeforeEach
    public void beforeEach(){
        business.setService(service);
    }

    @Test
    void calculateSumByService() {
        when(service.retriveData()).thenReturn(new int[] {1,2,3,4});
        assertEquals(10, business.calculateSumByService());
    }

    @Test
    void calculateSumByService_empty() {
        when(service.retriveData()).thenReturn(new int[] {});
        assertEquals(0, business.calculateSumByService());
    }
}

Junit5 using Mockito with annotation 

Here we don’t need to provide @BeforeEach to provide setters as in the above example.

package com.unittest.unittesting.business;

import com.unittest.unittesting.data.DataService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;


@ExtendWith(MockitoExtension.class)
class BusinessImplMock1Test {
    @InjectMocks
    BusinessImpl business;

    @Mock
    DataService service= mock(DataService.class);

    @Test
    void calculateSumByService() {
        when(service.retriveData()).thenReturn(new int[] {1,2,3,4});
        assertEquals(10, business.calculateSumByService());
    }

    @Test
    void calculateSumByService_empty() {
        when(service.retriveData()).thenReturn(new int[] {});
        assertEquals(0, business.calculateSumByService());
    }
}

Mockito with a list class, different return values, different arguments,  generic arguments.

package com.unittest.unittesting.business;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;


@ExtendWith(MockitoExtension.class)
class MockListTest {

    @Test
    void size_basics() {
        List mock=mock(List.class);
        when(mock.size()).thenReturn(5);
        assertEquals(5,mock.size());
    }

    @Test
    void size_basics_return_diff_values() {
        List mock=mock(List.class);
        when(mock.size()).thenReturn(5).thenReturn(10);
        assertEquals(5,mock.size());
        assertEquals(10,mock.size());
    }

    @Test
    void return_with_parameters() {
        List mock=mock(List.class);
        when(mock.get(0)).thenReturn(5);
        assertEquals(5,mock.get(0));
        assertEquals(10,mock.get(1)); //It will return null if specific value not specified.
    }

    @Test
    void return_with_generic_parameters() {
        List mock=mock(List.class);
        when(mock.get(anyInt())).thenReturn(5);
        assertEquals(5,mock.get(0));
        assertEquals(5,mock.get(1));
    }
}

Verify method calls

List mock=mock(List.class);

@Test
    void verify_method_call(){
        //SUT
        Integer val1= (Integer) mock.get(0);
        Integer val2= (Integer) mock.get(1);

        //Verify method calls
        verify(mock).get(0);
        verify(mock,times(2)).get(anyInt());
        verify(mock,atLeast(1)).get(anyInt());
        verify(mock,atLeastOnce()).get(anyInt());
        verify(mock,atMost(2)).get(anyInt());
        verify(mock,never()).get(2);
    }

Argument Capturing

@Test
   void argument_capturing(){
       //SUT
       mock.add("myString");

       //Verification
       ArgumentCaptor<String > captor= ArgumentCaptor.forClass(String.class);
       verify(mock).add(captor.capture());

       assertEquals("myString",captor.getValue());
   }

   @Test
   void multiple_argument_capturing(){
       //SUT
       mock.add("myString1");
       mock.add("myString2");

       //Verification
       ArgumentCaptor<String > captor= ArgumentCaptor.forClass(String.class);
       verify(mock,times(2)).add(captor.capture());

       assertEquals("myString1",captor.getAllValues().get(0));
       assertEquals("myString2",captor.getAllValues().get(1));

   }

Spying

// We work just on mock or template that we design for method.
   @Test
   void mocking(){
       ArrayList mock=mock(ArrayList.class);
       mock.add(1); //It won't be stored
       System.out.println(mock.size());  // 0 size because it's mock.
       System.out.println(mock.get(0));  // 0 because it's mock.
       when(mock.size()).thenReturn(5);  // after setting only it will return specified value
       System.out.println(mock.size());  // 5 size because we specified.
   }

   // We work on real implementation for method.
   @Test
   void spying(){
       ArrayList spy=spy(ArrayList.class);
       spy.add(1); //It won't be stored
       System.out.println(spy.size());  // 1 size because it's spy.
       System.out.println(spy.get(0));  // 1 because it's spy.
       when(spy.size()).thenReturn(5);  // after setting we get the control and loose original implementation.
       System.out.println(spy.size());  // 5 size because we specified.
   }

 

Loading

11 People reacted on this

Leave a Comment