1

i am using spring tool suite to write a code .there are 4 layers restContoller,buisnesslogic,domain ,service.... i want to test for a method of business logic layer where it calls a method of dao which finally calls a method of service layer to return a simple primitive value... to make it clear in the businesslogic class i have autowired domain class ,and in the domain class i have autowired the service classs..the problem that i am facing iss when i run the test class i am getting NullPointerException i am attaching the code for the test class... kindly help if possible

@ExtendWith(MockitoExtension.class)
class CustomerBlTest {
    @Mock
    CustomerService mockService;
    @Autowired
    CustomerDO customerDo;

    @Autowired
    @InjectMocks
    CustomerBl bl;       //buisnesslogic class
    @Test
    void checkForGetInteger() {
        when(mockService.getIntegerFfromService()).thenReturn(3);

        int actual = bl.getInteger();
        Assertions.assertEquals(3, actual);
    }
}

2 Answers2

0

Since you are extending MockitoExtension hence this test class is not aware of spring. But you are still using @Autowired annotation. So that's wrong. Remove all @AUtowired annotations in the test class. Besides this you do not need to bring in all the sterotyped classes. Bring in only the one that the class is using i.e. in your case the classes injected in CustomerBl class. I think that should be CustomerService class. So remove the CustomerDO class if it's not being used in CustomerBl class. The @InjectMock and @MOck annotation have been applied correclty. I think that should help you get your result.

sushil
  • 1,576
  • 10
  • 14
0

You need to use @Mock instead of @Autowired as shown below.

@ExtendWith(MockitoExtension.class)
class CustomerBlTest {
    @Mock
    CustomerService mockService;

    @Mock
    CustomerDO customerDo;

   
    @InjectMocks
    CustomerBl bl;       //buisnesslogic class

    @Test
    void checkForGetInteger() {
        when(mockService.getIntegerFfromService()).thenReturn(3);

        int actual = bl.getInteger();
        Assertions.assertEquals(3, actual);
    }
}
SSK
  • 3,444
  • 6
  • 32
  • 59