Я пытаюсь протестировать API, используя JUNIT и mockito, будучи новичком, я не нашел никакого решения в отношении проблемы, которую я заявляю
Я пытаюсь протестировать API, который включает включение сотрудникаи отдел в виде
{
"name": "ABC",
"age": 20,
"salary": 2500.0,
"departmentTest": {
"deptId": 5,
"deptName": "Developer"
}
}
Это должно быть тело почтового запроса.Здесь существует соотношение один к одному между сотрудником и отделом.Многие сотрудники могут принадлежать к одному отделу, и отображение является двунаправленным.
Я получаю следующее исключение: -
**org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at com.example.controller.EmployeeTestController.addEmployee(EmployeeTestController.java:45)**
Настоящим я прилагаю файл Controller, Service and Testing: -
Файл контроллера: -
@Controller
public class EmployeeTestController {
@Autowired
private EmployeeTestService employeeTestService;
@GetMapping("/employee")
public ResponseEntity<?> getAllEmployee()
{
return new ResponseEntity<>(employeeTestService.getAllEmployee(),HttpStatus.OK);
}
@PostMapping("/employee")
public ResponseEntity<?> addEmployee(@Valid @RequestBody EmployeeTestDTO employeeTestDTO) throws EmployeeException
{
if(employeeTestDTO.getSalary() <= 0 ){
throw new EmployeeException("Salary Should be greater than Zero");
}
else {
employeeTestService.addEmployee(employeeTestDTO);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
}
Сервисный файл: -
@Service
public class EmployeeTestService {
@Autowired
private EmployeeTestRespository employeeTestRespository;
@Autowired
private DepartmentTestService departmentTestService;
@Autowired
private ModelMapper modelMapper;
public List<EmployeeTestDTO> getAllEmployee()
{
List<EmployeeTestDTO> empDTO = new ArrayList<EmployeeTestDTO>();
List<EmployeeTest> emp=employeeTestRespository.findAll();
for(EmployeeTest e : emp)
{
empDTO.add(modelMapper.map(e, EmployeeTestDTO.class));
}
return empDTO;
}
public Object getIndividualEmployee(Integer id) throws EmployeeException {
Optional<EmployeeTest> op_employeeTest = employeeTestRespository.findById(id);
if(op_employeeTest.isPresent())
{
return modelMapper.map(op_employeeTest.get(), EmployeeTestDTO.class);
}
else
{
throw new EmployeeException("No such employee exist");
}
}
public void addEmployee(EmployeeTestDTO employeeTestDTO) throws EmployeeException {
String dept_name = modelMapper.map(employeeTestDTO, EmployeeTest.class).getDepartmentTest().getDeptName();
DepartmentTest departmentTest = departmentTestService.findDepartmentByDeptName(dept_name);
if(departmentTest == null){
throw new EmployeeException("Department doesn't exist");
}
else {
EmployeeTest employeeTest = modelMapper.map(employeeTestDTO,EmployeeTest.class);
employeeTest.setDepartmentTest(departmentTest);
employeeTestRespository.save(employeeTest);
}
}
Файл тестирования: -
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = EmployeeTestController.class)
@ContextConfiguration(classes = IntegrationTestingForEmployeeApplication.class)
public class ControllerTesting {
private MockMvc mockMvc;
@MockBean
private EmployeeTestService employeeTestService;
@InjectMocks
private EmployeeTestController employeeTestController;
@MockBean
private ModelMapper modelMapper;
DepartmentTest departmentTest ;
EmployeeTest employeeTest;
@Before
public void setUp()throws Exception
{
System.out.println("Inside Set Up Method");
mockMvc = MockMvcBuilders.standaloneSetup(employeeTestController)
.build();
departmentTest = new DepartmentTest();
departmentTest.setDeptId(1);
departmentTest.setDeptName("Sales");
}
@Test
public void controllerTesting() throws Exception
{
System.out.println(departmentTest.getDeptId());
System.out.println(departmentTest.getDeptName());
String json = "{\"name\":\"ABC\",\"age\":20,\"salary\":2500,\"departmentTest\":{\"deptId\":5,\"deptName\":\"Developer\"}}";
mockMvc.perform(post("/employee")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name", Matchers.is("ABC")))
.andExpect(jsonPath("$.age", Matchers.is(20)))
.andExpect(jsonPath("$.salary", Matchers.is(2500)));
}
}