为在 Junit mockito 测试用例中自动装配的嵌套 bean 抛出空指针异常

问题描述 投票:0回答:1

我有用于服务层的 Junit 测试用例,从服务方法逻辑调用一些具有自动装配功能的其他 bean,并且在单元测试用例中,我将该 bean 用作 Autowired,因为它也应该作为代码覆盖率的一部分进行覆盖。

class CustomerServiceTest{

   @Autowired(or InjectMocks)
   private EmployeeService employeeService;

   @Autowired
   private CustomerService customerService;

   @Test
   public void testcustomerIdNotNull() {
       //mocking some repository call
       Customer customer = customerService.getCustomerDetails();
       //all other test case code
   }
}

 //Customer Service code
 @Service
 public class CustomerService{

 @Autowired
 EmployeeService employeeService;

 public Customer getCustomerDetails() {
       //some code
      employeeService.getEmployee();   /// **Here it was throwing nullpointerexception** 
    //some logic and complete code
 }
}

我尝试使用 Spy 进行 Autowired 但没有成功。

java spring-boot junit mockito code-coverage
1个回答
0
投票

如果测试类使用以下注释进行注释,它将起作用

@RunWith(SpringRunner.class)
@SpringBootTest

但这会加载整个 Spring 应用程序上下文,更适合集成测试。

从单元测试的角度来看,建议将

@RunWith(MockitoJUnitRunner.class)
@InjectMocks
@Mock
组合使用

@RunWith(MockitoJUnitRunner.class)
class CustomerServiceTest{
   @Mock
   private EmployeeService employeeService;

   @InjectMocks
   private CustomerService customerService;

   @Test
   public void testcustomerIdNotNull() {
       //mocking some repository call
       Customer customer = customerService.getCustomerDetails();
       //all other test case code
   }
}

使用Junit4约定

© www.soinside.com 2019 - 2024. All rights reserved.