Currently, I am working on the sample demo application for learning purposes, in which I have implemented the CRUD operations for the Tutorial.
Here is my sample code to create a new tutorial:
TutorialsController.java
public class TutorialsController {
@Autowired
TutorialService tutorialService;
@PostMapping("/tutorials")
public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
try {
Tutorial _tutorial = tutorialService.createTutorial(tutorial);
return new ResponseEntity<>(_tutorial, HttpStatus.CREATED);
} catch (Exception | BaseException e) {
logger.info("Error:: {}", e.getMessage());
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
TutorialServiceImpl.java
@Service
public class TutorialServiceImpl implements TutorialService {
public Tutorial createTutorial(Tutorial tutorial) {
If(Utility.checkToggle) {
throw new BadRequestException("Validation faild for given tutorial. Please check provided parameters")
} else {
return tutorialRepository.save(
new Tutorial(tutorial.getTitle(), tutorial.getDescription(), tutorial.getAuthor(), false)
);
}
}
}
I have a static method checkToggle
in the Utility class which performs some toggle check and if the given check gets failed I am raising BadRequestException.
Now I am trying to test the scenario where the toggle check is failed. Here is my sample code
@RunWith(PowerMockRunner.class)
@PrepareForTest({TutorialsController.class})
public class TutorialsControllerTest {
@InjectMocks
TutorialsController tutorialsController;
@Mock
TutorialServiceImpl tutorialServiceImpl;
@Test
public void test1() {
Tutorial tutorial = new Tutorial();
tutorial.setAuthor("Test");
tutorial.setDescription("Test");
PowerMockito.mockStatic(Utility.class);
when(Utility.checkToggle()).thenReturn(true);
ResponseEntity<Tutorial> response = tutorialsController.createTutorial(tutorial);
assertEquals(response.getStatusCode(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
But my test case is failing. After debugging found that Utility.checkToggle() method is not getting mocked.
So can you please let me know why this is happening? And how to fix this.
For implementing the test case I followed https://ngdeveloper.com/how-to-test-controller-using-powermock-in-spring-boot/ tutorial.