代码之家  ›  专栏  ›  技术社区  ›  David

如何在Junit的服务类中模拟依赖关系

  •  -1
  • David  · 技术社区  · 1 年前

    我正在尝试编写我的一种服务方法的测试用例。我正在打包错误,无法调用

    Cannot invoke "com.company.app.models.Product.getId()" 因为“product”为null

    这是我的服务课

    @Service
    @Log4j2
    @Transactional
    @RequiredArgsConstructor(onConstructor = @__({ @Autowired, @Lazy }))
    public class SomeService {
    
      private final AccountRepository accountRepository;
      private final AccountMapper accountMapper;
      private final ProductService productService;
     
    
      public Account doSomeOperation(AccountRequest accountRequest) throws ResourceNotFoundException {
        Product product = productService.findByName(accountRequest.getProductName());
        Account account = (accountRequest.getId() != null) ? accountRepository.findById(accountRequest.getId())
            .orElseThrow(() -> new ResourceNotFoundException("Account Not found with id - " + accountRequest.getId()))
            : new Account();
    
        accountMapper.merge(accountRequest, account);
        account.setProductId(product.getId());
        return accountRepository.save(account);
      }
    

    这是我的服务课

    @WebMvcTest(MigrationService.class)
    
    
    class MigrationServiceTest {
    
    
        @Mock
        private AccountRepository accountRepository;
    
        @Mock
        private ProductService productService;
    
        @Mock
        private AccountMapper mapper;
    
        @InjectMocks
        private SomeService someService;
    
        
     @Test
     void testDoSomeOperation() throws ResourceNotFoundException {
        // Arrange
        AccountRequest accountRequest = new AccountRequest();
        accountRequest.setProductName(“myProduct”);
        Product product = new Product();
        product.setId(1L);
        when(accountRepository.findById(any())).thenReturn(java.util.Optional.of(new Account()));
        when(accountRepository.save(any(Account.class))).thenReturn(new Account());
    
        // Act
        Account migratedAccount = migrationService.migrateAccount(accountRequest);
    
        // Assert
        assertNotNull(migratedAccount);
        assertEquals(product.getId(), migratedAccount.getProductId());
        // Add more assertions as needed
    }
    
    
    }
    

    现在我已经检查了数据库中可用的myProduct in数据库表。但在这一生中,我没有得到的值是null Product Product=productService.findByName(accountRequest.getProductName());

    我缺少什么?

    1 回复  |  直到 1 年前
        1
  •  1
  •   Nawnit Sen    1 年前

    你正在传递的模拟实例 productService 但你不是在嘲笑这个方法 findByName 。因此,当在模拟实例上调用此方法时,您将获得null作为返回值。在下面添加一行以模拟产品服务上的方法。

    when(productService.findByName(any())).thenReturn(new Product());