Junit 与 Mockito for java

问题描述 投票:0回答:1

我正在学习 java 并使用 Mockito 探索 junit。 这个想法是了解在哪里以及如何使用mockito并学习如何编写junit测试。我是初学者,正在学习。

我如何使用mockito为以下代码编写junit测试:

public class QueryBuilder<EntityT> {
private List<List<String>> allConditions;
private int top;
private int skip;
private FieldOrdering ordering;
private String tableName;

public QueryBuilder() {
    this.allConditions = new ArrayList<>();
    this.top = -1;
    this.skip = 0;
    this.ordering = new FieldOrdering();
    this.tableName = "your_table"; // Default table name
}

public QueryBuilder<EntityT> filter(FilterableExpression filters) {
    allConditions.add(filters.getConditions());
    return this;
}

public QueryBuilder<EntityT> and() {
    allConditions.get(allConditions.size() - 1).add(" AND ");
    return this;
}

public QueryBuilder<EntityT> or() {
    allConditions.get(allConditions.size() - 1).add(" OR ");
    return this;
}

public QueryBuilder<EntityT> top(int count) {
    this.top = count;
    return this;
}

public QueryBuilder<EntityT> skip(int count) {
    this.skip = count;
    return this;
}

public QueryBuilder<EntityT> orderBy(FieldOrdering ordering) {
    this.ordering = ordering;
    return this;
}

public QueryBuilder<EntityT> tableName(String tableName) {
    this.tableName = tableName;
    return this;
}

/**
 * build the query with the clauses addded to Filter Expression *
 * 
 * @return
 */
public String build() {
    StringBuilder query = new StringBuilder("SELECT * FROM " + tableName + " WHERE ");

    if (!allConditions.isEmpty()) {
        for (int i = 0; i < allConditions.size(); i++) {
            List<String> conditions = allConditions.get(i);
            for (int j = 0; j < conditions.size(); j++) {
                query.append(conditions.get(j));
                if (j < conditions.size() - 1 && !conditions.get(j + 1).equals(" AND ")
                        && !conditions.get(j + 1).equals(" OR ")) {
                    query.append(" ");
                }
            }
            if (i < allConditions.size() - 1) {
                query.append(" AND ");
            }
        }
    } else {
        query.append("1=1");
    }

    List<String> orderByList = ordering.getOrderByList();
    if (!orderByList.isEmpty()) {
        query.append(" ORDER BY ").append(String.join(", ", orderByList));
    }

    if (top > 0) {
        query.append(" LIMIT ").append(top);
    }

    if (skip > 0) {
        query.append(" OFFSET ").append(skip);
    }

    return query.toString();
}

}

非常感谢任何帮助/建议。我想编写测试,检查流程并了解一切是如何工作的。

提前致谢。

java junit mockito junit4
1个回答
0
投票

@模拟 查询生成器查询生成器;

@测试 无效模拟构建方法测试(){

字符串预定义=“一些预定义的SQL”;

Mockito.doReturn(预定义) .when(查询生成器) .build();

Assertions.assertEquals(预定义, queryBuilder.build());

}

© www.soinside.com 2019 - 2024. All rights reserved.