Check/Test if RedirectView will redirect to specific url

Georgi Michev :

I have endpoint where I need to check if the user is logged in and if this is not the case to redirect to the login page. I am throwing custom exception and after that using exception handler in other class like this

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    private final DomainsService domainsService;

    @ExceptionHandler(value = {UserNotLoggedInException.class})
    protected RedirectView handleUserNotLoggedException() {
        String defaultDomainName = domainsService.getDefaultDomainName();
        String loginUrl = "https://" + defaultDomainName + "/login.php";
        return new RedirectView(loginUrl);
    }

} 

I am able to test the fetching of the loginUrl and it is correct but I dont have any UI where I can test if this logic will indeed redirect to the login url. I think there is possibility to test with MockMvc but then I need to specify the url and the url is fetched from the database so I can not just hardcode an url

Ali Ben Zarrouk :

You got it right with MockMvc. Only thing you re missing is to inject a mock for DomainService.

You can have DomainsService an interface and implement it for test and for prod using @Profile. In your test you can return url of your test server and verify in your test that the endpoint is hit.

Also btw I think you're missing something in your @ControllerAdvice. @ControllerAdvice(basePackageClasses = MyRestController.class)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=422855&siteId=1