I’m developing an API using Java Spring. It has a controller, a service and a repository, in the repository I deserialize a JSON file and populate a list. I want to create unit tests for the repository. How do I mock this list, so I don’t change it during testing? I’m having doubts regarding the concept of unit tests, should this list be mocked or can I use the list that is used in the repository?
I already tried to inject the list into my test class, but it remains empty.
ArnoldZ1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
You can use Mockito
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MyRepositoryTest {
@InjectMocks
private MyRepository repository;
@Mock
private List<String> mockList;
@Before
public void setUp() {
// Populate mockList with test data if necessary
when(mockList.size()).thenReturn(3);
when(mockList.get(0)).thenReturn(new String("a"));
when(mockList.get(1)).thenReturn(new String("b"));
when(mockList.get(2)).thenReturn(new String("c"));
when(repository.getList()).thenReturn(mockList);
}
@Test
public void testRepositoryMethod() {
// Your test logic here
// Use repository.getList() and verify behavior
}
}
2