我有一个项目与以下类:
@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);
它工作正常,哪里会有问题?
1条答案
按热度按时间6fe3ivhb1#
我通过添加注解
@SpringBootTest
解决了该问题