getter 的 junit 测试方法设定者

发布于 2024-08-21 09:15:27 字数 699 浏览 5 评论 0原文

我的项目中有很多java bean。我需要为它们生成一个 JUnit Test 类。使用Eclipse 3.2 & 生成的测试方法junit 4.4 如下所示:

public void testGetName() {
        // fail("Not yet implemented");
    }

    @Test
    public void testSetName() {
        // fail("Not yet implemented");
    }

    @Test
    public void testGetEmployeeid() {
        // fail("Not yet implemented");
    }

    @Test
    public void testSetEmployeeid() {
        // fail("Not yet implemented");
    }

我的一些 bean 有超过 100 个字段...

有没有一种方法可以让我获得 getter 和 getter 的单一测试方法?像 testEmployeeid()testName() 这样的设置器,以便在这些方法中我可以测试我的设置器和设置器。 getter 而不是使用 2 diff。他们的测试方法...

我应该如何配置 eclipse 来做到这一点?

I have many java beans in my project. I need to generate a JUnit Test class for them. The test methods generated using Eclipse 3.2 & junit 4.4 look like the following:

public void testGetName() {
        // fail("Not yet implemented");
    }

    @Test
    public void testSetName() {
        // fail("Not yet implemented");
    }

    @Test
    public void testGetEmployeeid() {
        // fail("Not yet implemented");
    }

    @Test
    public void testSetEmployeeid() {
        // fail("Not yet implemented");
    }

some of my beans have more than 100 fields...

Is there a way by which I can get a single test method for both the getters & setters like testEmployeeid(), testName() so that in these methods I can test both my setters & getters rather than using 2 diff. test methods for them...

How should I configure eclipse to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

美男兮 2024-08-28 09:15:27

测试驱动开发的哲学是“测试一切可能破坏的东西”。也就是说,将精力集中在有用的测试上,而不是仅仅为了测试而编写测试。

Getter 和 Setter 几乎总是琐碎的代码,不值得自己测试。

我知道这不是对您请求的直接回答,但我认为指出这一点仍然可能有帮助;-)那么为什么您实际上需要首先为所有这些 getter 和 setter 编写测试呢?

The philosophy of Test Driven Development says "test everything which can possibly break". That is, focus your efforts on the useful tests, instead of writing tests for just the sake of it.

Getters and setters are almost always trivial code, which is not worth testing by themselves.

I know this is not a straight answer to your plea, but I thought it may still help to point this out ;-) So why do you actually need to write tests for all those getters and setters in the first place?

甜妞爱困 2024-08-28 09:15:27

如果你的类中有 100 个字段(带有相应的 setter/getter),我怀疑你的对象模型没有正确分解。对于一个对象来说,100 多个字段听起来像是一个非常多的字段,我猜想它有几个职责,可以分为多个更专门的对象。

If you have 100 fields in a class (with corresponding setters/getters) I suspect your object model is not decomposed correctly. 100+ fields sounds like an extraordinary number of fields for an object, and I would guess that it has several responsibilities that can be split across a number of more specialised objects.

娇纵 2024-08-28 09:15:27

您也许可以使用 Apache Commons 'beanutils' 来帮助自动执行此操作:

http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/PropertyUtils.html#getSimpleProperty%28java.lang.Object ,java.lang.String%29

例如,有一个方法 describe(Object bean) 它将返回所有可读属性(即 getter)的映射。

然后迭代该映射并调用:

setSimpleProperty(Object bean, String name, Object value)

虽然

public static Object getSimpleProperty(Object bean, String name)

我同意其他海报,但 getter/setter 非常微不足道 - 我认为仍然值得测试它们 - 以消除拼写错误,测试属性更改监听器等。

例如,这将动态提取bean 的 getter:

import java.io.Serializable;
import java.util.Set;
import org.apache.commons.beanutils.PropertyUtils;

public class MyTestBean implements Serializable {
    private int a;
    private int b;
    private int c;
    private String x;
    private String y;
    private String z;

    public static void main(String[] args) throws Exception {
    MyTestBean bean=new MyTestBean();
    Set prop=PropertyUtils.describe(bean).keySet();
    for (Object o : prop) {
        System.out.println((String)o);
    }
    }

    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public int getB() {
        return b;
    }
    public void setB(int b) {
        this.b = b;
    }
    public int getC() {
        return c;
    }
    public void setC(int c) {
        this.c = c;
    }
    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
    public String getY() {
        return y;
    }
    public void setY(String y) {
        this.y = y;
    }
    public String getZ() {
        return z;
    }
    public void setZ(String z) {
        this.z = z;
    }}

您需要将 BeanUtils 和 CommonsLogging 以及这两个库的 JAR 下载到您的项目中才能运行此代码。

You could perhaps use Apache Commons 'beanutils' to help automate this:

http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/PropertyUtils.html#getSimpleProperty%28java.lang.Object,java.lang.String%29

For instance there is a method describe(Object bean) which will return a map of all the readable attributes (ie, getters).

Then iterate that map and call:

setSimpleProperty(Object bean, String name, Object value)

and

public static Object getSimpleProperty(Object bean, String name)

And although I agree with the other poster than getters/setters are pretty trivial - I think it is still worth testing them - to eliminate typos, test property change listeners etc.

For example, this will dynamically extract the getters of a bean:

import java.io.Serializable;
import java.util.Set;
import org.apache.commons.beanutils.PropertyUtils;

public class MyTestBean implements Serializable {
    private int a;
    private int b;
    private int c;
    private String x;
    private String y;
    private String z;

    public static void main(String[] args) throws Exception {
    MyTestBean bean=new MyTestBean();
    Set prop=PropertyUtils.describe(bean).keySet();
    for (Object o : prop) {
        System.out.println((String)o);
    }
    }

    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public int getB() {
        return b;
    }
    public void setB(int b) {
        this.b = b;
    }
    public int getC() {
        return c;
    }
    public void setC(int c) {
        this.c = c;
    }
    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
    public String getY() {
        return y;
    }
    public void setY(String y) {
        this.y = y;
    }
    public String getZ() {
        return z;
    }
    public void setZ(String z) {
        this.z = z;
    }}

You will need to download both BeanUtils and CommonsLogging and both libraries' JARs to your project to run this code.

贪了杯 2024-08-28 09:15:27

我想这个库就是您问题的答案: http://outsidemybox.github.com/testUtils/

它测试所有 bean 的初始值、setter、getter、hashCode()、equals() 和 toString()。您所要做的就是定义默认和非默认属性/值的映射。

它还可以测试带有附加非默认构造函数的 bean 对象。

I guess this library is the answer to your question: http://outsidemybox.github.com/testUtils/

it tests all the bean's initial values, the setters, the getters, hashCode(), equals() and toString(). All you have to do is define a map of default and non default property/value.

It can also test objects that are beans with additional non default constructors.

猫腻 2024-08-28 09:15:27

2021 年回答这个问题,因为这个问题仍然存在。

Bean 会增加代码库,如果您的 DevOps 管道对存储库施加覆盖范围限制,则会产生非常负面的影响。有两种方法可以克服它。

  1. 排除豆子(我认为不应该这样做)。

  2. 为 bean 编写测试用例(这是我们作为开发人员可以做的最可悲的浪费时间的事情:( )。

在大多数情况下,您最终将为 bean 编写测试用例。

我编写了这个简单的实用程序/测试使用反射并允许您增加 Junit 代码覆盖率并节省您的测试时间的案例

: City

package com.test.beans;

import java.util.List;

/**
 * @author ameena
 *
 */
public class City {
    private int postOffices;
    private int jurdictaionAreas;
    private double areaInSqMeter;
    private long population;
    private List<City> neighbourCities;
    private boolean metro;

    public int getJurdictaionAreas() {
        return jurdictaionAreas;
    }

    public void setJurdictaionAreas(int jurdictaionAreas) {
        this.jurdictaionAreas = jurdictaionAreas;
    }

    public double getAreaInSqMeter() {
        return areaInSqMeter;
    }

    public void setAreaInSqMeter(double areaInSqMeter) {
        this.areaInSqMeter = areaInSqMeter;
    }

    public long getPopulation() {
        return population;
    }

    public void setPopulation(long population) {
        this.population = population;
    }

    public int getPostOffices() {
        return postOffices;
    }

    public void setPostOffices(int postOffices) {
        this.postOffices = postOffices;
    }

    public List<City> getNeighbourCities() {
        return neighbourCities;
    }

    public void setNeighbourCities(List<City> neighbourCities) {
        this.neighbourCities = neighbourCities;
    }

    public boolean isMetro() {
        return metro;
    }

    public void setMetro(boolean metro) {
        this.metro = metro;
    }
}

用于自动化 bean 测试的类


package com.test.beans;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;

/**
 * @author ameena
 *
 */
class BeanTest {

    public void invokeSetter(Object obj, String propertyName, Object variableValue)
    {
        PropertyDescriptor propDescriptor;
        try {
            propDescriptor = new PropertyDescriptor(propertyName, obj.getClass());
            Method setter = propDescriptor.getWriteMethod();
            try {
                setter.invoke(obj,variableValue);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                e.printStackTrace();
                fail(e.getMessage());
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }

    }

    public Object invokeGetter(Object obj, String variableName)
    {
        Object returnValue = null;
        try {
            PropertyDescriptor pd = new PropertyDescriptor(variableName, obj.getClass());
            Method getter = pd.getReadMethod();
            returnValue = getter.invoke(obj);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
        return returnValue;
    }


    private <T extends Object> void validateGettersSetters(List<T> objects) {
        for (T t : objects) {
            Class<?> aClass = t.getClass();
            for (java.lang.reflect.Field field : aClass.getDeclaredFields()) {
                System.out.println(field);
                Class<?> c = field.getType();
                if (c == String.class) {
                    invokeSetter(t, field.getName(), "dummy");
                    assertEquals("dummy", (invokeGetter(t, field.getName())));
                } else if (c == Integer.class || c == int.class) {
                    invokeSetter(t, field.getName(), 1);
                    assertEquals(1, (invokeGetter(t, field.getName())));
                }else if (c == Double.class || c == double.class) {
                    invokeSetter(t, field.getName(), 1d);
                    assertEquals(1d, (invokeGetter(t, field.getName())));
                }else if (c == Long.class || c == long.class) {
                    invokeSetter(t, field.getName(), 1l);
                    assertEquals(1l, (invokeGetter(t, field.getName())));
                }else if (c == Boolean.class || c == boolean.class) {
                    invokeSetter(t, field.getName(), true);
                    assertEquals(true, (invokeGetter(t, field.getName())));
                }else if (c == List.class){
                    //Now based on your bean and filed name
                    switch(field.getName()) {
                    case "neighbourCities" :
                        invokeSetter(t, field.getName(), new ArrayList<City>());
                        assertNotNull(invokeGetter(t, field.getName()));
                        break;
                }
            }
        }
    }
    }

    @Test
    void testBean() {
        List<Object> objects = new ArrayList<>();
        objects.add(new City());
        validateGettersSetters(objects);

    }

}

没什么花哨的,但它节省了我为 23 个 bean 编写测试用例的时间:)

问候。
阿米特·米娜

Answering this in 2021 because this problem still persists.

Beans add up to the code base and have a very negative impact if your DevOps pipelines are imposing coverage restrictions on repos. There are two ways to overcome it.

  1. Exclude the beans ( which I would say should not be done).

  2. Write test cases for beans ( which is the most pathetic thing that we as a developer can do to waste our time :( ).

And in most cases, you will end up writing test cases for beans.

I have written this simple Utility/test case that uses reflection and can allow you to increase the Junit code coverage and save your time.

Bean under test: City

package com.test.beans;

import java.util.List;

/**
 * @author ameena
 *
 */
public class City {
    private int postOffices;
    private int jurdictaionAreas;
    private double areaInSqMeter;
    private long population;
    private List<City> neighbourCities;
    private boolean metro;

    public int getJurdictaionAreas() {
        return jurdictaionAreas;
    }

    public void setJurdictaionAreas(int jurdictaionAreas) {
        this.jurdictaionAreas = jurdictaionAreas;
    }

    public double getAreaInSqMeter() {
        return areaInSqMeter;
    }

    public void setAreaInSqMeter(double areaInSqMeter) {
        this.areaInSqMeter = areaInSqMeter;
    }

    public long getPopulation() {
        return population;
    }

    public void setPopulation(long population) {
        this.population = population;
    }

    public int getPostOffices() {
        return postOffices;
    }

    public void setPostOffices(int postOffices) {
        this.postOffices = postOffices;
    }

    public List<City> getNeighbourCities() {
        return neighbourCities;
    }

    public void setNeighbourCities(List<City> neighbourCities) {
        this.neighbourCities = neighbourCities;
    }

    public boolean isMetro() {
        return metro;
    }

    public void setMetro(boolean metro) {
        this.metro = metro;
    }
}

The class to automate the bean testing


package com.test.beans;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;

/**
 * @author ameena
 *
 */
class BeanTest {

    public void invokeSetter(Object obj, String propertyName, Object variableValue)
    {
        PropertyDescriptor propDescriptor;
        try {
            propDescriptor = new PropertyDescriptor(propertyName, obj.getClass());
            Method setter = propDescriptor.getWriteMethod();
            try {
                setter.invoke(obj,variableValue);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                e.printStackTrace();
                fail(e.getMessage());
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }

    }

    public Object invokeGetter(Object obj, String variableName)
    {
        Object returnValue = null;
        try {
            PropertyDescriptor pd = new PropertyDescriptor(variableName, obj.getClass());
            Method getter = pd.getReadMethod();
            returnValue = getter.invoke(obj);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
        return returnValue;
    }


    private <T extends Object> void validateGettersSetters(List<T> objects) {
        for (T t : objects) {
            Class<?> aClass = t.getClass();
            for (java.lang.reflect.Field field : aClass.getDeclaredFields()) {
                System.out.println(field);
                Class<?> c = field.getType();
                if (c == String.class) {
                    invokeSetter(t, field.getName(), "dummy");
                    assertEquals("dummy", (invokeGetter(t, field.getName())));
                } else if (c == Integer.class || c == int.class) {
                    invokeSetter(t, field.getName(), 1);
                    assertEquals(1, (invokeGetter(t, field.getName())));
                }else if (c == Double.class || c == double.class) {
                    invokeSetter(t, field.getName(), 1d);
                    assertEquals(1d, (invokeGetter(t, field.getName())));
                }else if (c == Long.class || c == long.class) {
                    invokeSetter(t, field.getName(), 1l);
                    assertEquals(1l, (invokeGetter(t, field.getName())));
                }else if (c == Boolean.class || c == boolean.class) {
                    invokeSetter(t, field.getName(), true);
                    assertEquals(true, (invokeGetter(t, field.getName())));
                }else if (c == List.class){
                    //Now based on your bean and filed name
                    switch(field.getName()) {
                    case "neighbourCities" :
                        invokeSetter(t, field.getName(), new ArrayList<City>());
                        assertNotNull(invokeGetter(t, field.getName()));
                        break;
                }
            }
        }
    }
    }

    @Test
    void testBean() {
        List<Object> objects = new ArrayList<>();
        objects.add(new City());
        validateGettersSetters(objects);

    }

}

Nothing fancy, but it saved me for writing test cases for 23 beans :)

Regards
Amit Meena

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文