I'm trying to test my @RestController
, but it doesn't work, giving me the error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studio.abos.springcalc.rest.ControllerTest': Unsatisfied dependency expressed through field 'restTemplate': No qualifying bean of type 'org.springframework.boot.web.server.test.client.TestRestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
This is my controller:
@RestController
public class Controller {
@PostMapping(path = "/calc-simple", produces = "application/json")
public BigResults calcSimple(final @RequestBody BigParameters params) {
// ...
}
}
This is my test class:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
final class ControllerTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void invalidBigInteger1() {
final var testParams = new BigParameters("invalid", "6", List.of(), List.of(), 1);
restTemplate.postForObject("http://localhost:" + port + "/simple-calc", testParams, BigResults.class);
}
}
I saw similar but outdated posts where the solution was to add the RANDOM_PORT
annotation parameter, but I already did that. How can I fix it?
How about using the org.springframework.boot.test.web.client.TestRestTemplate
instead of org.springframework.boot.web.server.test.client.TestRestTemplate
?
In the SpringBoot's documentation, the TestRestTemplate
is declared in the package org.springframework.boot.test.web.client
.
If you need to add a test dependency, try just like below.
For a gradle project
testImplementation 'org.springframework.boot:spring-boot-starter-test'
For a maven project
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>