-1

I have below java class for which i have to write a junit test.

@Service
class My {
    @Value("${emp.name}")
    private String name;

    public void printName() {
        StringBuilder sb = new StringBuilder(name);
        //do some stuff
    }
}

Now I'm writing a test class for this java class that is like below.

@PrepareforTest({My.class})
public class MyTest {
   @InjectMocks
   My my;

   @Test
   public void printNameTest() {
       //Test code
   }
}

The problem here is i'm getting null pointer exception on StringBuilder sb = new StringBuilder(name); and test is breaking.

Anyone know how to load properties values in the test using @Value or pass the values to instance. I tried using reflection but it also gave error.

Pirate
  • 2,886
  • 4
  • 24
  • 42

2 Answers2

0

Do not use field Injection, but instead pass it in the constructor. Makes it easier to test.

@Service
class My {

    private String name;

    public My(@Value("${emp.name}") String name) {
        this.name = name;
    }

    public void printName() {
        StringBuilder sb = new StringBuilder(name);
        //do some stuff
    }

}

Alternatively, use the ReflectionTestUtils. See: https://stackoverflow.com/a/17355595/2082699

Tom Cools
  • 1,098
  • 8
  • 23
0

There is no annotation to tell Mockito @InjectMocks to just inject that value without doing any mocking or spying.

So you have two option :

  1. either autowire My class and let's handle everything by springboot.
  2. or mock the printName() response
Abhishek Mishra
  • 611
  • 4
  • 11