【问题标题】:How to populate data for tests in spring data rest?如何在春季数据休息中填充测试数据?
【发布时间】:2023-04-10 22:08:01
【问题描述】:

我在使用自定义控制器对 Spring Data Rest 应用程序进行单元测试时遇到问题。

@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;
    }
}

我尝试通过发布数据来填充数据,但没有任何运气。似乎在单元测试中没有创建任何在运行应用程序时创建的映射,所以我得到的只是异常说没有映射到'system/...'等。

如您所见,我尝试通过存储库填充数据。而且它也不起作用,可能是一些事务问题,因为我可以在日志中看到插入语句,但数据库中没有任何内容。

我看到我可以提供一些 sql 脚本来填充数据,但这似乎很愚蠢,因为如果我们仍然使用 SQL 来完成这样的简单任务,为什么还要使用 ORM。

    @Before
    public void setup() throws Exception {

        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        channels.System system = new System("foo");

        GeometryFactory gf = new GeometryFactory();
        Channel[] channels = new Channel[]{
                new Channel(
                        1,
                        system,
                        gf.createPoint(new Coordinate(55.7565, 37.6153)),
                        1,
                        Arrays.asList(new String[]{"м. Охотный ряд"})
                ),
                new Channel(
                        1,
                        system,
                        gf.createPoint(new Coordinate(55.8079, 37.5808)),
                        1,
                        Arrays.asList(new String[]{"м. Дмитровская"})
                ),
                new Channel(
                        1,
                        system,
                        gf.createPoint(new Coordinate(50.4451, 30.5182)),
                        1,
                        Arrays.asList(new String[]{"м. Театральная"})
                ),

        };
        channelsRepository.save(Arrays.asList(channels));
        system.setChannels(Arrays.asList(channels));
        systemsRepository.save(system);
//        ClassLoader classLoader = getClass().getClassLoader();
//        String systemAsJson = IOUtils.toString(classLoader.getResourceAsStream("system.json"));
//        String channelsAsJson = IOUtils.toString(classLoader.getResourceAsStream("channels.json"));
//        JSONParser parser = new JSONParser();
//        JSONObject system = (JSONObject) parser.parse(systemAsJson);
//
//        String result = mockMvc.perform(post("/systems")
//                        .accept(MediaType.APPLICATION_JSON).
//                        content(system.toJSONString())
//                        ).andReturn().getResponse().getContentAsString();
//        System.out.println(result);
    }

【问题讨论】:

  • 你看过@Sql吗?
  • this page,它用于在测试期间以编程方式将数据插入数据库。

标签: java spring spring-mvc spring-data-rest


【解决方案1】:
  • 您看不到数据库中的更改,因为(如果您使用AbstractTransactionalSpringContextTests)spring 会在测试执行后清理事务。所以里面的测试方法数据是可用的。

  • 使用sql脚本并不傻,可能适用于很多情况。

  • 看看TestNGru

【讨论】:

  • 我看不到如何在您提供的最后一个链接中填充数据。但无论如何,我已经能够适当地构建 mockmvc 以便导出资源,现在我实际上可以在测试前后发布和删除数据
【解决方案2】:

我已经添加了 webapplication contet,现在我可以通过 perform(post()) 和 perform(delete) 方法发布和删除数据,我现在还可以。

  @Autowired
    private WebApplicationContext context;

    private JSONArray channels;
    @Before
    public void setup() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 2013-03-23
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2013-07-04
    相关资源
    最近更新 更多