java—如何使用JUnit5测试songservlet中的方法

tvmytwxo  于 2021-07-11  发布在  Java
关注(0)|答案(0)|浏览(231)

我的任务是测试一个用java编写的httpservlet,它连接到一个数据库并实现了以下方法:
doget(),dopost(),dodelete(),dooptions()
为了独立于数据库连接测试功能,我实现了一个inmemorydao,它用json文件中的测试数据填充h2数据库,并注入到我的servlettest类中。
下面是doget()方法的一个示例:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {

    boolean all = req.getParameter("all") != null;
    boolean specific = req.getParameter("songId") != null;

    if (all == specific) {
        resp.setStatus(400);
        writePlaintext(resp, "Specify either 'all' or 'songId'.");
        return;
    }

    if (all) doGetAll(req, resp);
    if (specific) doGetSpecific(req, resp);
}

我记忆中的松岛课是这样的:

public class InMemorySongDao extends MysqlSongDao {

public InMemorySongDao() throws SQLException {
    super(new ComboPooledDataSource());
    UUID uuid = UUID.randomUUID();

    // Connect to a unique in-memory database identified by a random uuid
    this.dataSource.setJdbcUrl("jdbc:h2:mem:" + uuid);
    try (PreparedStatement st = this.dataSource.getConnection().prepareStatement(
            "CREATE TABLE songs (" +
                    "id int not null primary key auto_increment," +
                    "title varchar(100) not null," +
                    "artist varchar(100)," +
                    "label varchar(100)," +
                    "released int" +
                    ")")) {
        st.execute();
    }
}

/**
 * Creates a songs dao prefilled with the songs from the given resource.
 */
public InMemorySongDao(String resourceName) throws SQLException, IOException {
    this();
    final ObjectMapper mapper = new ObjectMapper();
    JsonNode rootNode = mapper.readTree(getClass().getResource(resourceName));

    // Read array node or use empty node
    ArrayNode array = (rootNode.isArray()) ? (ArrayNode) rootNode : mapper.createArrayNode();
    try (PreparedStatement st = this.dataSource.getConnection().prepareStatement("INSERT INTO songs (id, title, artist, label, released) values (?,?,?,?,?)")) {
        // Iterate over the array and populate the database with the songs
        Iterator<JsonNode> elements = array.elements();
        while (elements.hasNext()) {
            JsonNode node = elements.next();
            if (!node.isObject()) continue;
            st.setInt(1, node.get("id").asInt());
            st.setString(2, node.get("title").asText());
            st.setString(3, node.get("artist").asText());
            st.setString(4, node.get("label").asText());
            st.setInt(5, node.get("released").asInt());
            st.addBatch();
        }
        st.executeBatch();
    }
  }
}

如果有人能帮我的话我会非常感激的。不幸的是,通过研究我找不到任何合适的例子。。。
谢谢你,麦克

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题