Junit测试用例未针对模拟JPA运行

时间:2020-09-19 09:54:19

标签: junit mockito

我已经编写了示例CRUD方法。我已经为Service组件编写了JUnit测试用例,但是在运行测试时得到了“找不到地址ID ..”。

@测试 公共无效updateAddressTest()引发ResourceNotFoundException {

        Optional<Person> p = Optional.ofNullable(new Person( "Pranya", "Pune"));
        when(personRepository.existsById(1L)).thenReturn(true);
        
        
        Optional<Address> address = Optional.ofNullable(new Address( "zzz", "hyd","tel","1234"));
        
        when(repository.findById(1L)).thenReturn(address);
        
        Address addr1 = new Address( "zzz", "hyd","tel","1234");
        when(repository.save(addr1)).thenReturn(addr1);
        Address add= service.updateAddress(new Long(1L), new Long(1L),addr1);
        
        assertEquals(addr1,add );
    }





@Service
public class AddressService {

@Autowired
    private AddressRepository repository;
    
    @Autowired
    private PersonRepository personRepository;

public Address updateAddress(Long personId,
             Long addressId,Address addrRequest) throws ResourceNotFoundException {
        
         if (!personRepository.existsById(personId)) {
                throw new ResourceNotFoundException("personId not found");
            }

         return repository.findById(addressId).map(address -> {
                address.setCity(addrRequest.getCity());
                address.setState(addrRequest.getState());
                address.setStreet(addrRequest.getStreet());
                address.setPostalCode(addrRequest.getPostalCode());
                Person p = new Person();
                p.setId(personId);
                address.setPerson(p);
                
                return repository.save(address);
            }).orElseThrow(() -> new ResourceNotFoundException("address id not found.."));
    }
    
}

1 个答案:

答案 0 :(得分:0)

最有可能repository.save(address)返回null。您正在嘲笑该方法,但仅针对等于addr1的参数。在AddressService内部,创建了一个不同的地址实例。我猜想Address类没有实现equals方法(或在实现中包括person字段),所以when(repository.save(addr1)).thenReturn(addr1)与调用不匹配,并且返回了null

要解决此问题,请尝试使用Mockito.doAnswer代替Mockito.when

Mockito.doAnswer(invocation -> invocation.getArguments()[0]).when(repo).save(Mockito.any(Address.class));