Android 单元测试断言校验方法 org.junit.Assert

判断布尔值

assertTrue

assertFalse

判断对象非空

assertNull(object);

案例:

java 复制代码
PersistableBundle result = Util.getCarrierConfig(mockContext, subId);

assertNull(result);

判断是否相等

assertEquals("mocked_string", result.toString());

java 复制代码
package org.junit;

public class Assert {
    /**
     * Asserts that two objects are equal. If they are not, an
     * {@link AssertionError} without a message is thrown. If
     * <code>expected</code> and <code>actual</code> are <code>null</code>,
     * they are considered equal.
     *
     * @param expected expected value
     * @param actual the value to check against <code>expected</code>
     */
    public static void assertEquals(Object expected, Object actual) {
        assertEquals(null, expected, actual);
    }
}

可以用于字符串比较,比如下面的查询条件拼接

java 复制代码
//测试类
public class ApnSettingsTest {

    @Test
    public void testGetFillListQuery_initialWhereEmpty() {
        StringBuilder where = new StringBuilder();
        int subId = 1;

        // Mock the behavior of getSelection method
        when(mFragment.getSelection("", subId)).thenReturn("mocked_selection");

        StringBuilder result = mFragment.getFillListQuery(where, subId);

        // Verify the `where` has the expected selection
        assertEquals("mocked_selection", result.toString());

        // Check log output (Could use a library or a custom handler to intercept logs)
        // For simplicity, assuming log validation is part of the manual test validation process.
    }

    //TODO: 存在问题的测试接口,为什么其他两个getSelection可以返回预期??
    @Test
    public void testGetFillListQuery_initialWhereNonEmpty() {
        StringBuilder where = new StringBuilder("existing_condition");
        int subId = 1;

        // Mock the behavior of getSelection method,没生效?
        when(mFragment.getSelection("existing_condition", subId)).thenReturn(" AND mocked_selection");

        StringBuilder result = mFragment.getFillListQuery(where, subId);

        // Verify the `where` has the expected selection
        // 校验存在问题
        assertEquals("existing_condition AND mocked_selection", result.toString());

        // Check log output similarly as mentioned in previous test
    }

    @Test
    public void testGetFillListQuery_differentSubId() {
        StringBuilder where = new StringBuilder();
        int subId = 2;

        // Mock the behavior of getSelection method
        when(mFragment.getSelection("", subId)).thenReturn("different_selection");

        StringBuilder result = mFragment.getFillListQuery(where, subId);

        // Verify the `where` has the expected selection
        assertEquals("different_selection", result.toString());

        // Check log output similarly as mentioned in previous tests
    }

}


//被测试类
public class DemoSettings {

    @VisibleForTesting
    StringBuilder getFillListQuery(StringBuilder where, int subId) {
        String selection = "";
        selection = getSelection(selection, subId);
        where.append(selection);    // 拼接新增的过滤条件
        return where;
    }

    /**
     * Customize the cursor select conditions with subId releated to SIM.
     */
    String getSelection(String selection, int subId) {

        boolean isCustomized = true;
        Context context = getContext();
        if (context != null) {
            isCustomized = SubscriptionManager.getResourcesForSubId(getContext().getApplicationContext(), subId)
                    .getBoolean(R.bool.config_is_customize_selection);
        }

        if(!isCustomized) return selection;

        // 注意有两个双引号的地方:第一个转义",第二个是字符串匹配
        // 拼接的查询语句等效于:
        // (type = 0 or sub_id = $传入值)
        // SQL 查询语句:
        // SELECT *
        // FROM your_table
        // WHERE status = 'active' AND (type = "0" OR sub_id = "subId");
        String where = "(" + " type =\"" + "0" + "\"";
        where += " or sub_id =\"" + subId + "\"";
        where += " or type =\"" + "2" + "\"" + ")";
        selection = selection + " and " + where;
        return where;
    }

    // Additional tests could be written to consider edge cases, such as:
    // - Negative subId values
    // - Null or invalid StringBuilder where value
    // In real scenario, depending on codebase other relevant checks can also be added.

}

上述代码校验存在问题,报错如下:

Expected :existing_condition AND mocked_selection

Actual :existing_condition and (type ="0" or sub_id ="1" or type ="2")

<Click to see difference>

org.junit.ComparisonFailure: expected:<existing_condition [AND mocked_selection]> but was:<existing_condition [and (type ="0" or sub_id ="1" or type ="2")]>

修改后pass的逻辑,因为内部会自己创建where值,不知道为什么不按 when.thenReturn 的返回 mocked_selection。

java 复制代码
    @Test
    public void testGetFillListQuery_initialWhereNonEmpty() {
        StringBuilder where = new StringBuilder("existing_condition");
        int subId = 1;

        // Mock the behavior of getSelection method
        when(mFragment.getSelection("", subId))
                .thenReturn(" and (type ='0' or sub_id ='1' or type ='2')");

        StringBuilder result = mFragment.getFillListQuery(where, subId);

        // Verify the `where` has the expected selection
        assertEquals("existing_condition and (type ='0' or sub_id ='1' or type  ='2')",
                result.toString());
    }
相关推荐
白衣衬衫 两袖清风15 小时前
SQL联查案例
数据库·sql
程序员汤圆16 小时前
软件测试面试题总结【含答案】
测试工具·单元测试·测试用例
晨曦54321019 小时前
MySQL MOD()函数详解与Python对比
sql
甘露s19 小时前
MySQL深入之索引、存储引擎和SQL优化
数据库·sql·mysql
偶遇急雨洗心尘20 小时前
记录一次服务器迁移时,数据库版本不一致导致sql函数报错和系统redirect重定向丢失域名问题
运维·服务器·数据库·sql
Logic10120 小时前
《Mysql数据库应用》 第2版 郭文明 实验5 存储过程与函数的构建与使用核心操作与思路解析
数据库·sql·mysql·学习笔记·计算机网络技术·形考作业·国家开放大学
小二·20 小时前
MyBatis基础入门《十六》企业级插件实战:基于 MyBatis Interceptor 实现 SQL 审计、慢查询监控与数据脱敏
数据库·sql·mybatis
小二·21 小时前
MyBatis基础入门《十二》批量操作优化:高效插入/更新万级数据,告别慢 SQL!
数据库·sql·mybatis
百锦再21 小时前
国产数据库的平替亮点——关系型数据库架构适配
android·java·前端·数据库·sql·算法·数据库架构
卓码软件测评1 天前
第三方软件CMA/CNAS测评机构:【Apifox的自定义加密和签名的安全测试技巧】
测试工具·ci/cd·单元测试·测试用例·压力测试