我有服务方法"customerDetails"获取更多关于客户的信息,并使用其中的另一个方法更改一些字段& getById"当我对customerDetails进行单元测试时,我模拟了另一个方法,但测试失败了,因为模拟返回null。我尝试了一些解决方案,我发现像检查依赖关系的顺序和使用@InjectMocks(我这样做),但他们不适合我,我不知道问题在哪里。
的代码片段,以更好地理解我
customerService
public class customerService {
public Customer customerDetails(int id) {
CustomerDto customer = getById(id) //here is the problem
// rest of the code
}
public CustomerDto getById(int id) {
Optional<Customer> customer =
this.customerRepository.findCustomerByIdAndIsDeletedFalse(id); //return null here
if (!customer.isPresent()) {
// code to throw Exception customer not found
}
//code to retrieve customer
}
}
customerServiceTest
public class CustomerServiceTest {
@Mock
private CustomerRepository customerRepository;
@InjectMocks
private CustomerService customerService;
@BeforeEach
public void createMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCustomerDetails() {
CustomerDto actualResponse = DummyCutomer.createDto(); // the actualResponse is filled successfully
when(customerService.getById(actualResponse.getId()).thenReturn(actualResponse); // but here it send to getById null !!
//rest of code
}
}
您需要模拟customerRepository
而不是getById
方法例如:
when(customerRepository.findCustomerByIdAndIsDeletedFalse(actualResponse.getId()).thenReturn(Optional.of(WHAT_EVER_YOU_WANT));
在你的情况下,我认为你有两种情况:
findCustomerByIdAndIsDeletedFalse =比;可选的。属于(客户实例)findCustomerByIdAndIsDeletedFalse =比;Optional.empty ()