I have, for example, these classes with Spring Boot. I try to do a REST API without a database and wieh files as data. The data files are like this:
{ "persons": [ { "firstName":"John", "lastName":"Boyd", "address":"1509 Culver St", "city":"Culver", "zip":"97451", "phone":"841-874-6512", "email":"jaboyd@email.com" }, { "firstName":"Jacob", "lastName":"Boyd", "address":"1509 Culver St", "city":"Culver", "zip":"97451", "phone":"841-874-6513", "email":"drk@email.com" } ] }
@Repository
public class PersonRepository {
private List<Person> persons;
private DataLoaderService loaderService;
@Autowired
public PersonRepository(DataLoaderService loaderService){
persons = loaderService.convertJsonToPojo("Persons",Person.class);
}
public List<Person> getAll(){
return persons;
}
}
@Service
public class DataLoaderService {
private JsonFileService jsonFileService;
private ObjectMapper mapper
@Autowired
public DataLoaderService(JsonFileService jsonFileService,ObjectMapper mapper){
this.jsonFileService = jsonFileService;
this.mapper = mapper;
}
public <T> List<T> convertJsonToPojo(String nodeName, Class <T> classOfT){
}
}
So, I have a file. How can I read to transform to a list of Pojo?
When I want to mock the test method getAll()
, my list size is 0. The mock doesn't give me values because I think the problem is that I initialized the value in the constructor. Here is my test:
@ExtendWith(MockitoExtension.class)
public class PersonRepositoryTest {
PersonRepository repository;
@Mock
private DataLoaderService loaderService;
@BeforeEach
public void setUp() {
repository = new PersonRepository(loaderService);
}
@Test
public void getAllPersonnesInConstructor() {
List<Person> mockedList = Arrays.asList(
new Person("Paul","Moes","1", "7777", "adresse tour", "Chicago", "pauln@gmail.com"),
new Person("Eleson","Moc","2", "77777", "ddkdkd", "New York", "eleson@gmail.com")
);
doReturn(mockedList).when(loaderService).convertJsonToPojo("persons",Person.class);
List<Person> persons = repository.getAll();
assertEquals(2,persons.size(),"Expected list size is 2");
assertEquals(persons,mockedList);
}
}
If i use @Spy
, I have an error.
When I use method getAll()
without initializing the variable persons in the constructor but in the method getAll
, it is OK, like this:
public List<Person> getAll() {
this.persons = this.dataLoaderService.convertJsonToPojo("persons", Person.class);
log.debug("persons getALL repository" + persons);
return this.persons;
}
What can I do to test it?
Test a method which initializes a value in the constructor.