Sobes.tech
Junior

Milyen okok vannak a Wrapper osztályok használata mögött?

sobes.tech MI

Válasz az MI-től

  • Privát metódusok tesztelése
  • Örökölt kóddal való integráció
  • Komplex felületek "könnyítése"
  • További funkciók biztosítása (naplózás, metrikák, hibakezelés)
  • Külső könyvtárak alkalmazása a projekt követelményeihez
  • Külső szolgáltatások viselkedésének szimulálása (mockok, stubok)

Például, egy wrapper a privát metódus teszteléséhez Java-ban:

import java.lang.reflect.Method;

public class PrivateMethodWrapper {

    private Object instance;
    private Class<?> clazz;

    public PrivateMethodWrapper(Object instance) {
        this.instance = instance;
        this.clazz = instance.getClass();
    }

    public Object invokePrivateMethod(String methodName, Object... args) throws Exception {
        Method method = clazz.getDeclaredMethod(methodName, getParameterTypes(args));
        method.setAccessible(true);
        return method.invoke(instance, args);
    }

    private Class<?>[] getParameterTypes(Object... args) {
        Class<?>[] types = new Class<?>[args.length];
        for (int i = 0; i < args.length; i++) {
            types[i] = args[i].getClass();
        }
        return types;
    }
}

A wrapper használata:

// Privát metódussal rendelkező osztály
class MyClass {
    private int privateMethod(int a, int b) {
        return a + b;
    }
}

// Privát metódus tesztelése wrapper segítségével
public class MyClassTest {
    public void testPrivateMethod() throws Exception {
        MyClass instance = new MyClass();
        PrivateMethodWrapper wrapper = new PrivateMethodWrapper(instance);
        Object result = wrapper.invokePrivateMethod("privateMethod", 2, 3);
        System.out.println("Eredmény: " + result); // Kimenet: Eredmény: 5
    }
}