当前位置: 首页 > 工具软件 > JMockit > 使用案例 >

JMockit

景令秋
2023-12-01
import java.util.Locale;

/**
 * @Author: DuanKun
 * @Date: 2021/12/2 23:01
 * @Version: 1.0
 */
// 一个简单的类,能用不同语言打招呼
public class HelloJMockit {
    // 向JMockit打招呼
    public String sayHello(){
        Locale locale = Locale.getDefault();
        if(locale.equals(Locale.CHINA)){
            // 在中国,就说中文
            return "你好,JMockit";
        }else{
            // 在其他国家,就说英文
            return "Hello,JMockit";
        }
    }
}
import mockit.Expectations;
import org.junit.Assert;
import org.junit.Test;

import java.util.Locale;

/**
 * @Author: DuanKun
 * @Date: 2021/12/2 23:22
 * @Version: 1.0
 */
public class HelloJMockitTest {
    @Test
    public void testSayHelloAtChina() {
        // 假设当前位置是在中国
        new Expectations(Locale.class){
            {
                Locale.getDefault();
                result = Locale.CHINA;
            }
        };
        // 断言说中文
        Assert.assertTrue("你好,JMockit".equals((new HelloJMockit().sayHello())));
    }

    @Test
    public void testSayHelloAtUS(){
        // 假设当前位置是在美国
        Expectations expectations = new Expectations(Locale.class){
            {
                Locale.getDefault();
                result = Locale.US;
            }
        };
        // 断言说英文
        Assert.assertTrue("Hello,JMockit".equals((new HelloJMockit()).sayHello()));
    }
}

import mockit.Expectations;
import mockit.Mocked;
import mockit.Verifications;
import org.junit.Assert;
import org.junit.Test;

/**
 * @Author: DuanKun
 * @Date: 2021/12/2 23:48
 * @Version: 1.0
 */
public class ProgramConstructureTest {
    // 这是一个测试属性
    @Mocked
    HelloJMockit helloJMockit;

    @Test
    public void test1() {
        // 录制(Record)
        new Expectations() {
            {
                helloJMockit.sayHello();
                // 期待上述调用返回是"hello,david",而不是返回"hello,JMockit"
                result = "hello,david";
            }
        };
        // 重放(Replay)
        String msg = helloJMockit.sayHello();
        Assert.assertTrue(msg.equals("hello,david"));
        // 验证(verification)
        new Verifications() {
            {
                helloJMockit.sayHello();

                times = 1;
            }
        };
    }

    @Test
    public void test2(@Mocked HelloJMockit helloJMockit /*这是一个测试参数*/) {
        // 录制(Record)
        new Expectations() {
            {
                helloJMockit.sayHello();

                // 期待上述调用返回是"hello,david",而不是返回"hello,JMockit"
                result = "hello,david";
            }
        };
        // 重放(Replay)
        String msg = helloJMockit.sayHello();
        Assert.assertTrue(msg.equals("hello,david"));
        // 验证(Verification)
        new Verifications(){
            {
                helloJMockit.sayHello();
                // 验证helloJMockit.sayHello()这个方法调用了1次
                times = 1;
            }
        };
    }
}

 类似资料: