javamock生成对象



import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;



public class Mock {

    private static final Boolean[] bools                 = new Boolean[] { true, false };

    private static final char[]    words                 = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
            'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

    private static final Random    r                     = new Random();

    private static final int       MAX_COLLECTION_LENGTH = 50;

    private static final int       MAX_STRING_LENGTH     = 30;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static <T> T mock(Class<T> clazz) {
        if (clazz == Character.class || clazz == Character.TYPE) {
            return (T) (Character) words[r.nextInt(words.length)];
        } else if (clazz == Boolean.class || clazz == Boolean.TYPE) {
            return (T) (Boolean) bools[r.nextInt(bools.length)];
        } else if (clazz == Long.class || clazz == Long.TYPE) {
            return (T) (Long) r.nextLong();
        } else if (clazz == Integer.class || clazz == Integer.TYPE) {
            return (T) (Integer) r.nextInt();
        } else if (clazz == Short.class || clazz == Short.TYPE) {
            return (T) (Short) new Integer(r.nextInt(127)).shortValue();
        } else if (clazz == Float.class || clazz == Float.TYPE) {
            return (T) (Float) r.nextFloat();
        } else if (clazz == Double.class || clazz == Double.TYPE) {
            return (T) (Double) r.nextDouble();
        } else if (clazz == String.class) {
            return (T) randString(r.nextInt(MAX_STRING_LENGTH));
        }

        try {
            T instance = clazz.newInstance();

            for (Field f : ReflectUtil.getFields(clazz)) {
                f.setAccessible(true);
                Length lengthAnno = f.getAnnotation(Length.class);

                if (f.getType() == Character.TYPE) {
                    f.setChar(instance, words[r.nextInt(words.length)]);
                } else if (f.getType() == Character.class) {
                    f.set(instance, words[r.nextInt(words.length)]);
                } else if (f.getType() == Boolean.TYPE) {
                    f.setBoolean(instance, bools[r.nextInt(bools.length)]);
                } else if (f.getType() == Boolean.class) {
                    f.set(instance, bools[r.nextInt(bools.length)]);
                } else if (f.getType() == Long.TYPE) {
                    f.setLong(instance, r.nextLong());
                } else if (f.getType() == Long.class) {
                    f.set(instance, r.nextLong());
                } else if (f.getType() == Integer.TYPE) {
                    f.setInt(instance, r.nextInt());
                } else if (f.getType() == Integer.class) {
                    f.set(instance, r.nextInt());
                } else if (f.getType() == Short.TYPE) {
                    f.setShort(instance, new Integer(r.nextInt(127)).shortValue());
                } else if (f.getType() == Short.class) {
                    f.set(instance, new Integer(r.nextInt(127)).shortValue());
                } else if (f.getType() == Float.TYPE) {
                    f.setFloat(instance, r.nextFloat());
                } else if (f.getType() == Float.class) {
                    f.set(instance, r.nextFloat());
                } else if (f.getType() == Double.TYPE) {
                    f.setDouble(instance, r.nextDouble());
                } else if (f.getType() == Double.class) {
                    f.set(instance, r.nextDouble());
                } else if (f.getType() == String.class) {
                    f.set(instance, randString(r.nextInt(MAX_STRING_LENGTH)));
                } else if (f.getType() == List.class) {
                    int size = r.nextInt(MAX_COLLECTION_LENGTH);
                    List<Object> list = new ArrayList<Object>(size);
                    ParameterizedType pt = null;
                    for (int i = 0; i < size; i++) {
                        pt = (ParameterizedType) f.getGenericType();
                        list.add(mock((Class) pt.getActualTypeArguments()[0]));
                    }
                    f.set(instance, list);
                } else if (f.getType() == Map.class) {
                    int size = r.nextInt(MAX_COLLECTION_LENGTH);
                    Map<Object, Object> map = new HashMap<Object, Object>();
                    ParameterizedType pt = null;
                    for (int i = 0; i < size; i++) {
                        pt = (ParameterizedType) f.getGenericType();
                        map.put(mock((Class) pt.getActualTypeArguments()[0]),
                                mock((Class) pt.getActualTypeArguments()[1]));
                    }
                    f.set(instance, map);
                } else if (f.getType() == Date.class) {
                    f.set(instance, new Date());
                } else {
                    f.set(instance, mock(f.getType()));
                }
            }

            return instance;
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    private static String randString(int count) {
        if (count == 0) {
            count = 1;
        }

        int length = words.length;
        char[] text = new char[count];
        for (int i = 0; i < count; i++) {
            text[i] = words[r.nextInt(length)];
        }

        return new String(text);
    }

}
你可以使用JavaMockito框架来生成随机对象的随机数据mock。 首先,你需要在你的项目中引入Mockito库。在Maven项目中,可以在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.11.2</version> </dependency> ``` 然后,你可以使用Mockito的@Mock注释来创建一个mock对象,并使用Mockito的when()方法来定义当调用对象的某个方法时应该返回什么。例如: ```java import org.mockito.Mock; import static org.mockito.Mockito.when; public class RandomObjectMocker { @Mock private RandomObject randomObject; public void mockRandomData() { // Mock 100 random objects with random data for (int i = 0; i < 100; i++) { // Define the behavior of the randomObject when its methods are called when(randomObject.getName()).thenReturn(getRandomName()); when(randomObject.getAge()).thenReturn(getRandomAge()); // ... and so on for other methods of the RandomObject class } } private String getRandomName() { // Generate a random name return "RandomName" + Math.random(); } private int getRandomAge() { // Generate a random age between 1 and 100 return (int) (Math.random() * 100) + 1; } } ``` 在上面的示例中,我们为RandomObject类创建了一个mock对象,并使用Mockito的when()方法定义了当调用它的方法时应该返回什么。然后,我们使用一个循环来mock 100个具有随机数据的RandomObject对象。 请注意,这只是一个简单的示例。如果你的RandomObject类有许多属性和方法,你需要为每个属性和方法都定义Mockito的when()方法的行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值