集成测试中JsonDeserializer的java Spring引导自动连接
我有一个应用程序,需要在JsonDeserializer中用Spring连接一个服务。问题是,当我正常启动应用程序时,它是有线的,但当我在测试中启动它时,它是空的
相关代码为:
JSON序列化程序/反序列化程序:
@Component
public class CountryJsonSupport {
@Component
public static class Deserializer extends JsonDeserializer<Country> {
@Autowired
private CountryService service;
@Override
public Country deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {
return service.getById(jsonParser.getValueAsLong());
}
}
}
域对象:
public class BookingLine extends AbstractEntity implements TelEntity {
.....other fields
//Hibernate annotations here....
@JsonDeserialize(using = CountryJsonSupport.Deserializer.class)
private Country targetingCountry;
..... other fields
}
测试等级:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
@WebIntegrationTest({"server.port=0"})
@ActiveProfiles("test")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class BookingAndLinesControllerFunctionalTest {
@Test
public void testGetBooking() {
Booking booking = bookingRepositoryHelper.createBooking();
bookingRepository.save(booking);
String uri = String.format("http://localhost:%s/api/v1/booking-and-lines/" + booking.getBookingCode(), port);
Booking booking1 = restTemplate.getForObject(uri, Booking.class); // line which falls over because countryService is null
}
}
有什么想法吗
# 1 楼答案
花了足够长的时间才找到了这个问题的答案。只需要这样的配置: