我有这个密码。
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = ApiDbApplication.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource(
locations = "classpath:application.yml")
@ExtendWith(SpringExtension.class)
@Transactional
public class LocationIT {
@MockBean
CompanyRepository companyRepository;
@MockBean
ShipmentRepository shipmentRepository;
@MockBean
ContactRepository contactRepository;
private LocationController locationController;
private LocationService locationService;
@Autowired
LocationRepository locationRepository;
@LocalServerPort
private int port;
TestRestTemplate restTemplate = new TestRestTemplate();
HttpHeaders headers = new HttpHeaders();
@Before
public void setup() {
locationService = new LocationService(locationRepository);
this.locationController = new LocationController(locationService);
}
@Test
public void testAddLocation() {
ObjectMapper mapper = new ObjectMapper()
.registerModule(new JavaTimeModule());
;
Location location = Location.builder()
.id(Long.valueOf(7))
.city("Fayetteville")
.lat(32.33)
.lon(37.49)
.name("Big place")
.State("Arkansas").build();
ResponseEntity<String> responseEntity = this.restTemplate
.postForEntity("http://localhost:" + port + "/api/location/save", location, String.class);
ResponseEntity<List<Location>> results = restTemplate.exchange("http://localhost:" + port + "/api/location/list",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Location>>(){});
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals(HttpStatus.OK, results.getStatusCode());
assertEquals(Collections.singletonList(location), results.getBody());
}
}
每当我运行测试时。我的位置存储库为空,并且我有@Repository注解。这是我得到的错误:没有类型为“com.example.apidb.location.LocationRepository”的合格Bean可用:至少应有1个符合自动连接候选条件的Bean。依赖关系注解:{}
我想使用restTemplate来命中端点,所以我宁愿不使用@DataJPATest
。
这个问题也差不多:How can I use @SpringBootTest(webEnvironment) with @DataJpaTest?
2条答案
按热度按时间ilmyapht1#
如果您运行的测试用例是您帖子中的实际测试用例,那么您就做错了
1.您正在混合JUnit4和JUnit5,这在单个类中不起作用。
@TestPropertySource
用于属性文件而不是yaml文件1.您应该自动连接
TestRestTemplate
,而不是创建它(这也允许您删除@LocalServerPort
,因为它已经设置为基本URL。1.您的
@Before
实际上没有意义,构建服务和控制器不会在测试中添加任何内容,它只会占用内存和执行时间。1.您的测试方法中的
ObjectMapper
没有使用,所以为什么要构造它呢?@SpringBootTest
可以计算出应用程序类本身。1.不需要
@AutoConfigureTestDatabase
,这只适用于@DataJpaTest
、@DataJdbcTest
等分片测试。话虽如此,我还是希望能有类似下面的效果
假设您在
src/test/resources
的application.yml
中配置了正确的数据源。qkf9rpyu2#
Johnyutts回答了这个问题,答案是添加@EnableJpaRepositories(basePackageClasses = { LocationRepository.class}