Java 如何在SpringDataREST中为测试填充数据?
我在使用自定义控制器对SpringDataREST应用程序进行单元测试时遇到问题Java 如何在SpringDataREST中为测试填充数据?,java,spring,spring-mvc,spring-data-rest,Java,Spring,Spring Mvc,Spring Data Rest,我在使用自定义控制器对SpringDataREST应用程序进行单元测试时遇到问题 @RepositoryRestResource(path = "channels") public interface ChannelsRepository extends PagingAndSortingRepository<Channel, Long> { } @RepositoryRestResource(path = "systems") public interface SystemRepo
@RepositoryRestResource(path = "channels")
public interface ChannelsRepository extends PagingAndSortingRepository<Channel, Long> {
}
@RepositoryRestResource(path = "systems")
public interface SystemRepository extends PagingAndSortingRepository<System, String>{
}
@RestController
public class SystemController {
private String query = "select a.id as fromId, b.id as toId\n" +
"from channel a, channel b\n" +
"where ST_Distance_Spheroid(\n" +
"\ta.coordinates,\n" +
"\tb.coordinates,\n" +
"\t'SPHEROID[\"WGS 84\",6378137,298.257223563]'\n" +
") <= :criticalDistance and a.id != b.id";
@Autowired
private EntityManager manager;
@Autowired
private SystemRepository repository;
@RequestMapping(value="systems/{systemId}/graph", method = RequestMethod.GET)
public Map<BigInteger, List<BigInteger>> createNeighbourhsGraph(@PathVariable("systemId") String systemId,
@RequestParam(value = "distance") double distance) {
List<Object[]> results = manager.createNativeQuery(query).setParameter("criticalDistance", distance).getResultList();
Map<BigInteger, List<BigInteger>> map = new HashMap<BigInteger, List<BigInteger>>();
for (Object[] result: results) {
BigInteger fromId = (BigInteger) result[0];
if (map.containsKey(fromId)) {
map.get(fromId).add((BigInteger) result[1]);
}
else {
List<BigInteger> neighbours = new ArrayList<BigInteger>();
map.put(fromId, new ArrayList<BigInteger>(Arrays.asList(new BigInteger[]{(BigInteger) result[1]})));
}
}
return map;
}
}
- 您无法看到数据库中的更改,因为(在您使用的情况下)spring会在测试执行后清理事务。因此,测试方法内部的数据是可用的
- 使用sql脚本并不愚蠢,在许多情况下可能都适用
- 看看TestNG
@Autowired
private WebApplicationContext context;
private JSONArray channels;
@Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
你看过
@Sql
了吗?看,它是用于在测试期间以编程方式将数据插入数据库的。我不知道如何在你给出的最后一个链接中填充数据。但无论如何,我已经能够适当地构建mockmvc,以便导出资源,现在我实际上可以在测试前后发布和删除数据
@Autowired
private WebApplicationContext context;
private JSONArray channels;
@Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();