Spock-模拟的存储库方法save()给出NullPointerException

时间:2018-11-05 12:09:10

标签: java unit-testing groovy spring-data-jpa spock

我正在使用Spock对我的应用程序中的服务进行单元测试。最近,我遇到了一个我不太了解的奇怪行为。

这是我的单元测试:

def setup() {
    parkingSessionRepository = Mock(ParkingSessionRepository.class)
    parkingSessionMapper = Stub(ParkingSessionMapper.class)

    parkingMeterService = new ParkingMeterService(parkingSessionRepository, parkingSessionMapper)
}

def "should start parking session for vehicle that doesn't have an active parking session"() {

    given:
    String testVehicleId = "AWC1342"
    long testParkingRateId = 1

    ParkingStartDTO testParkingStartDTO = ParkingStartDTO.builder()
            .vehicleId(testVehicleId)
            .parkingRateId(testParkingRateId)
            .build()

    ParkingSession testParkingSession = ParkingSession.builder()
    .vehicleId(testVehicleId)
    .parkingRate(ParkingRate.REGULAR)
    .build()

    parkingSessionMapper.fromParkingStartDTO(_) >> testParkingSession
    parkingSessionRepository.save(_ as ParkingSession) >> testParkingSession

    parkingSessionRepository.findByVehicleIdAndStopTimeIsNull(_ as String) >> Optional.empty()

    when:
    ParkingMeterResponseDTO parkingMeterResponseDTO = parkingMeterService.startParkingMeter(testParkingStartDTO)

    then:
    1 * parkingSessionRepository.save(_ as ParkingSession)

    parkingMeterResponseDTO.vehicleId == testVehicleId
    Assert.assertNotNull(parkingMeterResponseDTO.parkingSessionId)
    Assert.assertNotNull(parkingMeterResponseDTO.timestamp)
}

经过测试的服务方法的代码为:

public ParkingMeterResponseDTO startParkingMeter(final ParkingStartDTO parkingStartDTO) {

    String vehicleId = parkingStartDTO.getVehicleId();

    if (isParkingSessionAlreadyActive(vehicleId)) {
        throw new ParkingSessionAlreadyActiveException();
    } else {

        ParkingSession parkingSession = parkingSessionMapper.fromParkingStartDTO(parkingStartDTO);
        parkingSession.setStartTime(Timestamp.from(Instant.now()));
        parkingSession = parkingSessionRepository.save(parkingSession);

        return ParkingMeterResponseDTO.builder()
                .vehicleId(parkingSession.getVehicleId())
                .parkingSessionId(parkingSession.getId())
                .timestamp(parkingSession.getStartTime())
                .build();
    }
}

现在,当我运行单元测试时,'when'块出现了NullPointerException的结果(save()方法返回null)。但是,当我从'then'块中删除save()方法检查时-一切运行顺利,没有null。

这种行为可能是什么原因?我怀疑存储库存在一些模拟问题,但是我不确定幕后到底发生了什么以及如何解决该问题,因此“ then”块中的save()方法按预期工作了吗?

1 个答案:

答案 0 :(得分:2)

请检查Spock文档: http://spockframework.org/spock/docs/1.0/interaction_based_testing.html

部分:模拟和存根结合

组合:

given:
...
parkingSessionRepository.save(_ as ParkingSession) >> testParkingSession
...
then:
1 * parkingSessionRepository.save(_ as ParkingSession)

将无法正常工作。您必须使用一个表达式:

1 * parkingSessionRepository.save(_ as ParkingSession) >> testParkingSession