Reputation: 25
I want to test some endpint that return a redirect (302). I want to use TestRestTemplate to test it but I cant get it to not automatically follow the redirect. I just want to get the response not make the redirect request.
The documentation says that it should disable redirect handling by default if apache client is on classpath, but I dont find that to be the case.
I have tried adding apache http client as dependecy or test dependecy and it wont work.
First of all why is the TestRestTempalte not working like the documentation is suggesting? And secondly is there any way to configure it to work?
I'll add the very simple sample code here, its very simple to replicate:
@RestController
public class controller {
@GetMapping(path = "/redirect")
public void redirect(HttpServletResponse response) throws IOException {
response.sendRedirect("/test");
}
@GetMapping(path = "/test")
public String test() {
return "hello";
}
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class redirectTest {
@Autowired
TestRestTemplate rest;
@Test
void redirectTest() {
var response = rest.getForEntity("/redirect", String.class);
System.out.println("Response: " + response.getBody());
assertEquals(302, response.getStatusCode().value());
}
}
plugins {
id 'java'
id 'org.springframework.boot' version '3.4.0'
id 'io.spring.dependency-management' version '1.1.6'
}
group = 'example'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.apache.httpcomponents:httpclient:4.3.6'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}
The test fails because isntead of getting 302 redirecct it automatically follows it.
Upvotes: 1
Views: 57
Reputation: 4670
There is a thread about that here: https://github.com/spring-projects/spring-boot/issues/27360
You could also do this specific test with MockMvc.
Upvotes: 1