So I'm trying to test my api and its giving me a nullpointer exception when I try to use the repository.
Supposedly I have a h2 database for testing in my application.yml(inside test/resources) like this:
spring:
profiles:
active: test
datasource:
username:
password:
url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE;
platform: h2
Here is my ControllerAPItest.java
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureTestDatabase
class ControllerAPITest {
@Mock
CompaniaRepository companiaRepository;
@Mock
DefaultGroupRepository defaultGroupRepository;
@Mock
OfficeRepository officeRepository;
@InjectMocks
CompaniaServiceImpl companiaService;
ControllerAPI controllerAPI = new ControllerAPI(companiaService);
@BeforeEach
void setUp() {
Compania compania = new Compania();
compania.setName("companiaTest");
compania.setDominio("dominioTest");
compania.setAltas("altasTest");
compania.setBajas("bajasTest");
compania.setDefault_group(null);
compania.setOffice(null);
companiaRepository.save(compania);
}
@AfterEach
void tearDown() {
companiaRepository.deleteAll();
}
@Test
void getByField() {
}
@Test
void getCompanias() {
System.out.println(controllerAPI.GetCompanias());
}
}
And here is the output of the error I'm getting:
java.lang.NullPointerException at controller.ControllerAPI.GetCompanias(ControllerAPI.java:114) at controller.ControllerAPITest.getCompanias(ControllerAPITest.java:65)
It is pointing to the line that says:
companiaRepository.save(compania);
Here is the full Error: https://textdoc.co/eGmu72wa1ydEoJ4T
What is happening with my code?
Thanks!
Edit. here is my getCompanias in my controller.
@ResponseStatus(HttpStatus.OK)
@GetMapping()
public Map<String, List<Compania>> GetCompanias() {
Map<String, List<Compania>> mappedResult = Collections.singletonMap("result", companiaService.getCompanias());
return mappedResult;
// return companiaService.getCompanias();
}
That uses the companiaService here:
public List<Compania> getCompanias() {
return companiaRepository.findAll();
}
Thanks!