0

I am testing a class A that extends an abstract class B. Class B has a private member M which i want to set for testing.

  1. First part of the problem as i understand is to retrieve the class b from class A. For which i tried getSuperclass, which i think may not be the right way to do this. Although, I am able to retrieve the field desired using ````ReflectionTestUtils.findfield()``` but not able to use set field.
  2. Secondly when i try to set field (ReflectionUtils.setField(field_M, B, M_to_be_set)) it basically ends up in the following exception: java.lang.IllegalArgumentException: Can not set M field M to java.lang.Class I have tried to setField, but it is not able to find the field itself.

Thanks

Daemon
  • 1
  • 2
  • Does this answer your question? [How do I test a private function or a class that has private methods, fields or inner classes?](https://stackoverflow.com/questions/34571/how-do-i-test-a-private-function-or-a-class-that-has-private-methods-fields-or) – Randy Casburn May 27 '21 at 15:51
  • 1
    Is this unit testing you are attempting? If so, you should mock B, otherwise you are integration testing. How does the private member of B get set in the actual working application? If you are truly integration testing, then that dependency is clearly part of the integrated context and whatever sets the private member in the first place should be included and tested independently of A. It would be tested as part of the integration between B and whatever sets the private member in the first place. – Randy Casburn May 27 '21 at 15:55

1 Answers1

0

It seems you are passing wrong arguments to setField() method. Below solution is working for me. Could you please check and confirm if it solves your issue?

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

public class TestClass {

    @Test
    public void test1() {
        ClassA a = new ClassA();

        ReflectionTestUtils.setField(a, "m", "value");

        Object f = ReflectionTestUtils.getField(a, a.getClass().getSuperclass(), "m");

        assertEquals("value", f.toString());
    }

}

abstract class ClassB {
    private String m;
}


class ClassA extends ClassB {

}

pcsutar
  • 1,715
  • 2
  • 9
  • 14