user2000189
user2000189

Reputation: 519

SpringBoot Junit Testing Autowiring issue

I am trying to do junit testing using plain junit by calling the controller class method as below, when i am doing this, the @Autowired annotation for object creation returns me null instead of creating the object.

Example:

JunitClass:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestingJunit { 
    @Test
    public void testing() {
           APIController repo = new APIController();
           ResponseEntity<?> prod = repo.getNames(8646, 1);
           List<TestVO> ff = (List<TestVO>) prod.getBody();
           Assert.assertEquals("AA", ff.get(0).getName());
    }
}

Controller:

@Autowired
private ServiceClass serviceClass;

 public ResponseEntity<?> getNames(@PathVariable("aa") int aa, @RequestHeader(value = "version") int version){

serviceClass.callSomeMethod(); // **here i am getting null for serviceClass object**

}

Upvotes: 1

Views: 132

Answers (2)

Samarth
Samarth

Reputation: 773

You can inject your APIController bean instead of doing new APIController() by autowiring the same in test class. As by doing new APIController the ServiceClass instance was not created/injected hence giving a NullPointer Exception.

Below should be the test class.

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestingJunit { 

    @AutoWired
    APIController apiController; //apiController will be referring to bean Name

    @Test
    public void testing() {
           ResponseEntity<?> prod = apiController.getNames(8646, 1);
           List<TestVO> ff = (List<TestVO>) prod.getBody();
           Assert.assertEquals("AA", ff.get(0).getName());
    }
}

Upvotes: 0

gWombat
gWombat

Reputation: 517

It's because you manually instaniates your controller by doing APIController repo = new APIController();. Doing this, Spring does not inject your service because you explicitely controls your bean (and its dependencies).

Try inject your controller in your test instead.

Upvotes: 3

Related Questions