2

Lets say I have an entity named Foo with an id and a name (simplified the class):

public class Foo {

    private long id;
    private String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getId() {
        return id;
    }
}

In my application I don't want that the id is set anywhere manually. Because foo will only come from DB. So I don't created a setter for it.

Now I want JUnit test some method where I want instantiate foo. Is there a possibility to set the id just for the JUnit Test?

P.S.: A possible solution is to receive foo from the DB first and make the test. But want to avoid the DB call. And I am using Spring and jpa if its necessary to know.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
Patrick
  • 12,336
  • 15
  • 73
  • 115
  • 2
    `ReflectionTestUtils.setField(foo, "id", 1L);` something like that. – M. Deinum Jul 14 '16 at 08:35
  • You need a setter also if you recieve that data using jpa – Jens Jul 14 '16 at 08:35
  • 2
    You don't need a setter when using JPA. That depends on the mode you are using (field or property based). – M. Deinum Jul 14 '16 at 08:37
  • You can also use Mockito API's for such requirements – Jeet Jul 14 '16 at 08:41
  • 1
    You can use reflection (search for the keyword, you will find loads of information) or you could extend your class, create your own constructor and overwrite `getId()`. See also [how-to-test-a-class-that-has-private-methods-fields-or-inner-classes](http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes?rq=1) – markus_ Jul 14 '16 at 08:42
  • 1
    @M.Deinum Thanks. Perfect and easy solution. Never hear of `ReflectionTestUtils` before. If you want to provide an answer I will accept yours. – Patrick Jul 14 '16 at 08:47

1 Answers1

2

Thanks for M. Deinum's comment. Easy and perfect solution is to use ReflectionTestUtils.

@Test
public void testFoo() {
  Foo foo = new Foo();
  ReflectionTestUtils.setField(foo, "id", 1L);
  // assertion
}

Please note: ReflectionTestUtils comes from Spring: org.springframework.test.util.ReflectionTestUtils

Community
  • 1
  • 1
Patrick
  • 12,336
  • 15
  • 73
  • 115