Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to autowire RestTemplate for unit test

I have a service which uses an autowired instance of RestTemplate like below

@Service
class SomeAPIService {
    private RestTemplate restTemplate;

    SomeAPIService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.restTemplate.setRequestFactory(HttpUtils.getRequestFactory());
    }
}

Everything runs fine in non-test environment. But when I try to run following unit test in test profile, it starts complaining about unable to autowire rest template.

@RunWith( SpringJUnit4ClassRunner.class )
@SpringBootTest(classes = MyApplication.class, webEnvironment = RANDOM_PORT, properties = "management.port:0")
@ActiveProfiles(profiles = "test")
@EmbeddedPostgresInstance(flywaySchema = "db/migration")
public abstract class BaseTest {
}

@SpringBootTest(classes = SomeAPIService.class)
public class SomeAPIServiceTest extends BaseTest {
    @Autowired
    SomeAPIService someAPIService;

    @Test
    public void querySomeAPI() throws Exception {
        String expected = someAPIService.someMethod("someStringParam");
    }
}

Following is the detailed exception -

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someAPIService': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

Any clues?

like image 812
comiventor Avatar asked Dec 14 '25 02:12

comiventor


1 Answers

Following helped me get the correct dependencies autowired. The solution is to also include RestTemplate.class in list of classes given to SpringBootTest.

@SpringBootTest(classes = {RestTemplate.class, SomeAPIService.class})
class SomeAPIService {
    @Autowired
    SomeAPIService someAPIService;

    @Test
    public void querySomeAPI() throws Exception {
        String expected = someAPIService.someMethod("someStringParam");
    }
}

@Emre answer was helpful in guiding me towards the final solution.

like image 103
comiventor Avatar answered Dec 16 '25 19:12

comiventor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!