Spring Boot 为什么我得到空而不是嘲笑?

r3i60tvu  于 2023-02-19  发布在  Spring
关注(0)|答案(1)|浏览(79)

我有一个项目与以下类:

@Repository
public interface SensorRepository extends JpaRepository<Sensor, Long> {
}
@Service
@RequiredArgsConstructor
public class SensorsServiceImpl implements SensorService {
    private final SensorRepository sensorRepository;

    @Override
    @Transactional
    public Sensor save(Sensor sensor) {
        return sensorRepository.save(sensor);
    }

    ...
}

我创建了测试来尝试Mockito

@RunWith(MockitoJUnitRunner.class)
class SensorsServiceImplTest {
    @Mock
    private SensorRepository sensorRepository;

    @InjectMocks
    private SensorService sensorService;

    @Test
    public void wasSensorSaved(){
        Sensor sensor = Sensor.builder().id(1L).build();

        when(sensorRepository.save(sensor)).thenReturn(sensor);

        Sensor savedSensor = sensorService.save(sensor);

        assertThat(savedSensor).isNotNull();
    }
}

但是当我运行这个测试的时候,我得到了一个异常,sensorRepository不是mock,它是null。如果我在测试中得到了正确的mock,比如

SensorRepository sensorRepository1 = mock(SensorRepository.class);
        SensorService sensorService1 = new SensorsServiceImpl(sensorRepository1);

它工作正常,哪里会有问题?

6fe3ivhb

6fe3ivhb1#

我通过添加注解@SpringBootTest解决了该问题

相关问题