【问题标题】:Junit test case not running for mock JPAJunit 测试用例未针对模拟 JPA 运行
【发布时间】:2020-09-19 09:54:19
【问题描述】:

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

@测试 public void 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.."));
    }
    
}

【问题讨论】:

    标签: junit mockito


    【解决方案1】:

    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));
    
    

    【讨论】:

    • 问题出在这一行:Address add= service.updateAddress(new Long(1L), new Long(1L),addr1);
    • @user739115 我觉得这条线没问题。问题在于您模拟 AddressRepository 的方式(或 AddressService 实现)。请参阅我编辑的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多