Java反射学习,Junit中的应用(JMockit)

本文介绍了Java反射在创建和操作对象中的应用,并详细展示了如何使用JMockit和Mockito进行单元测试,包括对私有方法、静态方法、公有方法、接口和抽象类的模拟。提供了相关的Maven配置和测试代码示例,帮助开发者理解单元测试和Mock技术。
摘要由CSDN通过智能技术生成

目录

1.操作对象

2.反射代码

3.更多应用

3.1.Junit

3.2.Junit + JMockit (    ===【mockit.Mock】 ===)

链接

代码:Maven:POM

代码:Junit

4.其他Mock的代码   ( ===【org.mockito.Mockito】)

5.核心代码  (通过构造函数设定值)

■★★★扩展(另外一种 Mockio方式(含DBUnit)):Mockito (文章链接)


1.操作对象

package com.sxz.study.reflect;

public class Student {
    private String name;
    private Integer score;
    public Student() {}
    public Student(String name, Integer score) {
        this.name = name;
        this.score = score;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setScore(Integer score) {
        this.score = score;
    }
    public Integer getScore() {
        return score;
    }
}

2.反射代码

package com.sxz.study.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanUtil {
	public static void main(String[] args) {

		try {
			// 使用反射,动态生成Student对象
			Class clz = Class.forName("com.sxz.study.reflect.Student");
			Constructor construtor = clz.getConstructor(String.class, Integer.class);
			Object obj = clz.newInstance();
			
			// 使用反射,调用setName方法,设置对象的:名字
			Method setter = clz.getMethod("setName", String.class);
		    setter.invoke(obj, "zhangsan");
		    
			// 使用反射,调用getName方法,获取对象的:名字
			Method getter = clz.getMethod("getName");
		    System.out.println(getter.invoke(obj));
			
		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
				| SecurityException | IllegalArgumentException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

3.更多应用

3.1.Junit

===

Eclipse中 Junit 正常运行完了 可是方法覆盖率全红 解决办法 (附带②EclEmma插件安装方法④覆盖率抽出与合并)_sun0322的博客-CSDN博客_eclipse junit 覆盖率

===

3.2.Junit + JMockit (    ===【mockit.Mock】 ===)

链接

使用Junit4和JMockit进行单元测试_义臻的博客-CSDN博客

代码:Maven:POM

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
</dependency>
<dependency>
  <groupId>org.jmockit</groupId> 
  <artifactId>jmockit</artifactId> 
  <version>1.21</version>
</dependency>

代码:Junit

package com.khlin.test.junit.jmockit.demo;
 
import mockit.Deencapsulation;
import mockit.Expectations;
import mockit.Injectable;
import mockit.Mock;
import mockit.MockUp;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import mockit.Tested;
import mockit.Verifications;
import mockit.integration.junit4.JMockit;
 
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
 
import com.khlin.test.junit.jmockit.demo.jmockit.AbstractA;
import com.khlin.test.junit.jmockit.demo.jmockit.ClassA;
import com.khlin.test.junit.jmockit.demo.jmockit.ClassB;
import com.khlin.test.junit.jmockit.demo.jmockit.InterfaceB;
 
@RunWith(JMockit.class)
public class JMockitTest {
 
    /**
     * mock私有方法
     */
    @Test
    public void testPrivateMethod() {
 
        final ClassA a = new ClassA();
        // 局部参数,把a传进去
        new Expectations(a) {
            {
                Deencapsulation.invoke(a, "getAnythingPrivate");
                result = 100;
                times = 1;
            }
        };
 
        Assert.assertEquals(100, a.getAnything());
 
        new Verifications() {
            {
                Deencapsulation.invoke(a, "getAnythingPrivate");
                times = 1;
            }
        };
    }
 
    /**
     * mock私有静态方法
     */
    @Test
    public void testPrivateStaticMethod() {
 
        new Expectations(ClassA.class) {
            {
                Deencapsulation
                        .invoke(ClassA.class, "getStaticAnythingPrivate");
                result = 100;
                times = 1;
            }
        };
 
        Assert.assertEquals(100, ClassA.getStaticAnything());
 
        new Verifications() {
            {
                Deencapsulation
                        .invoke(ClassA.class, "getStaticAnythingPrivate");
                times = 1;
            }
        };
 
    }
 
    /**
     * mock公有方法
     */
    @Test
    public void testPublicMethod() {
        final ClassA classA = new ClassA();
        new Expectations(classA) {
            {
                classA.getAnything();
                result = 100;
                times = 1;
            }
        };
 
        Assert.assertEquals(100, classA.getAnything());
 
        new Verifications() {
            {
                classA.getAnything();
                times = 1;
            }
        };
    }
 
    /**
     * mock公有静态方法--基于行为
     */
    @Test
    public void testPublicStaticMethod() {
 
        new Expectations(ClassA.class) {
            {
                ClassA.getStaticAnything();
                result = 100;
                times = 1;
            }
        };
 
        Assert.assertEquals(100, ClassA.getStaticAnything());
 
        new Verifications() {
            {
                ClassA.getStaticAnything();
                times = 1;
            }
        };
    }
    
    /**
     * mock公有静态方法--基于状态
     */
    @Test
    public void testPublicStaticMethodBaseOnStatus() {
 
        MockUp<ClassA> mockUp = new MockUp<ClassA>() {
            @Mock
            public int getStaticAnything() { //注意这里不用声明为static
                return 100;
            }
        };
        
        Assert.assertEquals(100, ClassA.getStaticAnything());
    }
    
    /**
     * mock接口--基于状态
     */
    @Test
    public void testInterface() {
        
        InterfaceB interfaceB = new MockUp<InterfaceB>() {
            @Mock
            public int getAnything() {
                return 100;
            }
        }.getMockInstance();
        
        
        ClassA classA = new ClassA();
        classA.setInterfaceB(interfaceB);
        
        Assert.assertEquals(100, classA.getClassBAnything());
    }
    
    /**
     * mock接口
     */
    @Test
    public void testInterfaceBasedOnStatus() {
        final InterfaceB interfaceB = new ClassB();
        
        new Expectations(interfaceB) {
            {
                interfaceB.getAnything();
                result = 100;
                times = 1;
            }
        };
        
        ClassA classA = new ClassA();
        classA.setInterfaceB(interfaceB);
        
        Assert.assertEquals(100, classA.getClassBAnything());
        
        new Verifications() {
            {
                interfaceB.getAnything();
                times = 1;
            }
        };
    }
    
    
    
    /**
     * mock抽象类
     */
    @Test
    public void testAbstract() {
        AbstractA abstractA = new MockUp<AbstractA>() {
            @Mock
            public int getAbstractAnything(){
                return 100;
            }
            
            @Mock
            public int getAnything(){
                return 1000;
            }
        }.getMockInstance();
        
        Assert.assertEquals(100, abstractA.getAbstractAnything());
        
        Assert.assertEquals(1000, abstractA.getAnything());
    }
}

===

4.其他Mock的代码   ( ===【org.mockito.Mockito】)

https://blog.csdn.net/sxzlc/article/details/123195147

import org.mockito.Mockito;

5.核心代码  (通过构造函数设定值)

Class clazz = Class.forName("Student");
Constructor<?> con = clazz.getConstructor(String.class, int.class);
Student student = (Student) con.newInstance("MyName", 18);
Method method=clazz.getMethod("myMethod", String.class);
method.invoke(student, "gogogo");

■★★★扩展(另外一种 Mock方式(含DBUnit)):Mockito (文章链接)

Junit笔记(Mockito)_sun0322的博客-CSDN博客=

===

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值