admin管理员组

文章数量:1122846

I have a problem with mocking in the spock, my variabla systemTaskOptional is null, test throwing an error. Here is my code of test, and part of code with biznes logic, where is null throwing.

    def "should get system tasks and check if done - mark as success" () {
        given:
            systemTasksRepository.findByUserIdAndDoneFalse(_) >> getSystemTasksAll()
            userApiService.getById(_) >> UserSnapshot.builder().storeAuthorities(Set.of(StoreAuthoritySnapshot.builder().role(StoreRole.OWNER).build()))panyAuthority(CompanyAuthoritySnapshot.builder()panyId(1L).build()).build()
            systemTasksRepository.findByUserId(_) >> getSystemTasksAll()
            systemTasksRepository.findByUserIdAndByTaskCode(_,_) >> Optional.of(SystemTask.builder().build())
        when:
            List<SystemTaskSnapshot> snapshots = tasksService.getSystemTasksAndCheck(1L)
        then:
            snapshots.size() == 2
            1 * systemTasksRepository.findByUserIdAndByTaskCode(1L, RepositoryTasksService.SystemTaskTypes.CREATE_STORE)
            1 * systemTasksRepository.findByUserIdAndByTaskCode(1L, RepositoryTasksService.SystemTaskTypes.CREATE_COMPANY)
    }

        if (notDoneSystemTasks.contains(SystemTaskTypes.CREATE_COMPANY)) {
            CompanyAuthoritySnapshot authoritySnapshot = userApiService.getById(userId).getCompanyAuthority();
            if (Objects.nonNull(authoritySnapshot) && Objects.nonNull(authoritySnapshot.getCompanyId())) {
                Optional<SystemTask> systemTaskOptional = systemTasksRepository.findByUserIdAndByTaskCode(userId, SystemTaskTypes.CREATE_COMPANY); <- this is null
                systemTaskOptional.ifPresent(systemTask -> systemTask.setDone(true));
            }
        }

I define service like this:

private TasksMapper tasksMapper = Spy()
private SystemTasksRepository systemTasksRepository = Mock()
private UserApiService userApiService = Mock()

@Subject
private TasksService tasksService = new RepositoryTasksService(tasksMapper, systemTasksRepository, userApiService)

This is stacktrace:

Connected to the target VM, address: '127.0.0.1:51363', transport: 'socket'
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.vmplugin.v7.Java7$1 (file:/Users/developer/.m2/repository/org/codehaus/groovy/groovy/2.5.8/groovy-2.5.8.jar) to constructor java.lang.invoke.MethodHandles$Lookup(java.lang.Class,int)
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.vmplugin.v7.Java7$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

java.lang.NullPointerException
    at com.nvt.pupil.tasks.service.service.RepositoryTasksService.checkIfDone(RepositoryTasksService.java:53)
    at com.nvt.pupil.tasks.service.service.RepositoryTasksService.getSystemTasksAndCheck(RepositoryTasksService.java:38)
    at com.nvt.pupil.tasks.service.service.RepositoryTasksServiceSpec.should get system tasks and check if done - mark as success(RepositoryTasksServiceSpec.groovy:65)

I have a problem with mocking in the spock, my variabla systemTaskOptional is null, test throwing an error. Here is my code of test, and part of code with biznes logic, where is null throwing.

    def "should get system tasks and check if done - mark as success" () {
        given:
            systemTasksRepository.findByUserIdAndDoneFalse(_) >> getSystemTasksAll()
            userApiService.getById(_) >> UserSnapshot.builder().storeAuthorities(Set.of(StoreAuthoritySnapshot.builder().role(StoreRole.OWNER).build())).companyAuthority(CompanyAuthoritySnapshot.builder().companyId(1L).build()).build()
            systemTasksRepository.findByUserId(_) >> getSystemTasksAll()
            systemTasksRepository.findByUserIdAndByTaskCode(_,_) >> Optional.of(SystemTask.builder().build())
        when:
            List<SystemTaskSnapshot> snapshots = tasksService.getSystemTasksAndCheck(1L)
        then:
            snapshots.size() == 2
            1 * systemTasksRepository.findByUserIdAndByTaskCode(1L, RepositoryTasksService.SystemTaskTypes.CREATE_STORE)
            1 * systemTasksRepository.findByUserIdAndByTaskCode(1L, RepositoryTasksService.SystemTaskTypes.CREATE_COMPANY)
    }

        if (notDoneSystemTasks.contains(SystemTaskTypes.CREATE_COMPANY)) {
            CompanyAuthoritySnapshot authoritySnapshot = userApiService.getById(userId).getCompanyAuthority();
            if (Objects.nonNull(authoritySnapshot) && Objects.nonNull(authoritySnapshot.getCompanyId())) {
                Optional<SystemTask> systemTaskOptional = systemTasksRepository.findByUserIdAndByTaskCode(userId, SystemTaskTypes.CREATE_COMPANY); <- this is null
                systemTaskOptional.ifPresent(systemTask -> systemTask.setDone(true));
            }
        }

I define service like this:

private TasksMapper tasksMapper = Spy()
private SystemTasksRepository systemTasksRepository = Mock()
private UserApiService userApiService = Mock()

@Subject
private TasksService tasksService = new RepositoryTasksService(tasksMapper, systemTasksRepository, userApiService)

This is stacktrace:

Connected to the target VM, address: '127.0.0.1:51363', transport: 'socket'
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.vmplugin.v7.Java7$1 (file:/Users/developer/.m2/repository/org/codehaus/groovy/groovy/2.5.8/groovy-2.5.8.jar) to constructor java.lang.invoke.MethodHandles$Lookup(java.lang.Class,int)
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.vmplugin.v7.Java7$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

java.lang.NullPointerException
    at com.nvt.pupil.tasks.service.service.RepositoryTasksService.checkIfDone(RepositoryTasksService.java:53)
    at com.nvt.pupil.tasks.service.service.RepositoryTasksService.getSystemTasksAndCheck(RepositoryTasksService.java:38)
    at com.nvt.pupil.tasks.service.service.RepositoryTasksServiceSpec.should get system tasks and check if done - mark as success(RepositoryTasksServiceSpec.groovy:65)
Share Improve this question edited Nov 22, 2024 at 13:20 kriegaex 67.1k15 gold badges119 silver badges221 bronze badges asked Nov 22, 2024 at 10:29 Karol WolnyKarol Wolny 671 silver badge6 bronze badges 12
  • Let me polish my magic crystal to look at stacktrace. – talex Commented Nov 22, 2024 at 12:31
  • In my crystal ball I see you did not initialized tasksService properly. – talex Commented Nov 22, 2024 at 12:35
  • java.lang.NullPointerException at com.nvt.pupil.tasks.service.service.RepositoryTasksService.checkIfDone(RepositoryTasksService.java:53) at com.nvt.pupil.tasks.service.service.RepositoryTasksService.getSystemTasksAndCheck(RepositoryTasksService.java:38) at com.nvt.pupil.tasks.service.service.RepositoryTasksServiceSpec.should get system tasks and check if done - mark as success(RepositoryTasksServiceSpec.groovy:65) this is stacktrace – Karol Wolny Commented Nov 22, 2024 at 12:37
  • 1 It will be easier to read if you edit it inside the question. – talex Commented Nov 22, 2024 at 12:38
  • 2 Please stop debating invisible code. SO is not a discussion forum. Whatever happens in line 53 of RepositoryTasksService, it causes the NPE, possibly due to accessing mock fields or calling mock methods returning null. But this is pure speculation. Karol, it would be so much easier for everyone with a minimal reproducer. Like this, the question is only attracting close votes. – kriegaex Commented Nov 23, 2024 at 2:25
 |  Show 7 more comments

1 Answer 1

Reset to default 1

Going out on a limb as you didn't provide the actual code where the exception happens, but I can already see that you need to Combine Mocking and Stubbing. Otherwise, your mocks will return null for those calls.

    def "should get system tasks and check if done - mark as success" () {
        given:
            systemTasksRepository.findByUserIdAndDoneFalse(_) >> getSystemTasksAll()
            userApiService.getById(_) >> UserSnapshot.builder().storeAuthorities(Set.of(StoreAuthoritySnapshot.builder().role(StoreRole.OWNER).build())).companyAuthority(CompanyAuthoritySnapshot.builder().companyId(1L).build()).build()
            systemTasksRepository.findByUserId(_) >> getSystemTasksAll()
        when:
            List<SystemTaskSnapshot> snapshots = tasksService.getSystemTasksAndCheck(1L)
        then:
            snapshots.size() == 2
            1 * systemTasksRepository.findByUserIdAndByTaskCode(1L, RepositoryTasksService.SystemTaskTypes.CREATE_STORE) >> Optional.of(SystemTask.builder().build())
            1 * systemTasksRepository.findByUserIdAndByTaskCode(1L, RepositoryTasksService.SystemTaskTypes.CREATE_COMPANY) >> Optional.of(SystemTask.builder().build())
    }

本文标签: javaSpock Mock Not WorkingTest Throws NullPointerExceptionStack Overflow