【问题标题】:test returning NULL when saving保存时测试返回 NULL
【发布时间】:2021-09-06 13:00:24
【问题描述】:

我有这门课:

@Repository
public interface EnfantRepository extends JpaRepository<Enfant, Long> {

..
}

还有这项服务:

@Transactional
@Service
@Slf4j
public class EnfantService implements IEnfantService {

    public Enfant save (Enfant enfant) {
        return enfantRepository.save(enfant);
    }
}

还有这个测试:

@RunWith(MockitoJUnitRunner.class)
public class EnfantServiceTest {

    @Mock
    private EnfantRepository enfantRepository = mock(EnfantRepository.class);

    @InjectMocks
    private EnfantService enfantService;

    @Test
    public void testSave() {

        System.out.println(enfantService.save(Enfant.builder().build()));

        Assertions.assertThat
                (enfantService.save(Enfant.builder().build())).isNotNull();

    }
}

但保存后返回null,测试失败

【问题讨论】:

    标签: java spring junit mockito eclipselink


    【解决方案1】:

    EnfantServiceTest 类中,您已经模拟了 EnfantRepository 类,并且没有为模拟的 EnfantRepository 类中的方法提供实现。因此,调用任何方法都会返回 null。

    这里有两种方式:

    1. 使用 Mockito 的“when”和“then”为模拟类 EnfantRepository 的 save 方法存根。
    @RunWith(MockitoJUnitRunner.class)
    public class EnfantServiceTest {
    
       @Mock
       private EnfantRepository enfantRepository = mock(EnfantRepository.class);
    
       @InjectMocks
       private EnfantService enfantService;
    
       @Test
       public void testSave() {
    
           System.out.println(enfantService.save(Enfant.builder().build()));
           
           when(enfantRepository.save(any()).thenReturn(Long.of(1));
    
           Assertions.assertThat
                   (enfantService.save(Enfant.builder().build())).isNotNull();
    
       }
    }
    But this wont be a good way of testing the repository code. Rather,
    
    1. 在您的测试环境中使用像H2 这样的内存数据库,在这种情况下无需模拟存储库类。 在运行测试时,Spring 将启动 H2 数据库,然后它将连接到该数据库并从您的实体类创建表并针对该数据库执行所有查询。这将确保您的代码端到端按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 2019-05-27
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 2020-06-14
      • 2019-07-30
      相关资源
      最近更新 更多