I’m trying to mock a list of strings but it’s not working. I’m not able to figure out the problem

Tags: , ,



This is the class and the corresponding test I have written for it. Can someone please help me understand why System.out.println(a.size()) prints 0 , when it should print 1000?

WorkingwithLists.java

import java.util.ArrayList;
import java.util.List;

public class WorkingwithLists
{
    public static void main(String[] args) {

    }

    public void ListFunctions()
    {
        List<String > a=new ArrayList<>();
        System.out.println(a.size());
    }
}

WorkingwithListsTest.java

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.List;

import static org.mockito.Mockito.when;
import static org.testng.Assert.*;

public class WorkingwithListsTest
{
    @Mock
    private List<String> a;

    private WorkingwithLists workingwithLists;

    @BeforeMethod
    public void setup()
    {
        MockitoAnnotations.openMocks(this);
        workingwithLists=new WorkingwithLists();
    }

    @Test
    public void testListFunctions() throws Exception
    {
        when(a.size()).thenReturn(1000);

        workingwithLists.ListFunctions();

    }
}

Answer

I am not sure why you want that, but to achieve that you have to move the “List a” to class level in order to “Mock” and return whatever you want. I have below example working, Hope this helps :

import java.util.ArrayList;
import java.util.List;

public class WorkingwithLists{
    List<String > a=new ArrayList<>();
    
    public static void main(String[] args) {

    }

    public void ListFunctions(){
        System.out.println(a.size());
    }
}


import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.List;

@RunWith(MockitoJUnitRunner.class)
public class WorkingwithListsTest{

    @InjectMocks
    WorkingwithLists workingwithLists;

    @Mock
    private List<String> a;

    @Before
    public void setup(){
        Mockito.when(a.size()).thenReturn(1000);
    }

    @Test
    public void testListFunctions() throws Exception{

        workingwithLists.ListFunctions();
        Assert.assertTrue(true);
    }
}

Output : enter image description here



Source: stackoverflow