简体   繁体   中英

Spring Boot - test without spring context with Spock

I have a service class and method with signature:

@Service
public class FileService {
    ....
    ....
    public Optional<FileDescr> upload(MultipartFile uploadFile){...}

    public Resource downloadFile(int linkID){...}

}

And test file (Groovy):

import org.junit.experimental.categories.Category
import org.springframework.mock.web.MockMultipartFile
import spock.lang.Shared
import spock.lang.Specification

@Category(WithoutSpringContext)
class FileServiceTestWithoutSpringContext extends Specification{

    @Shared
    FileService fileService = Mock()

    @Shared
    MockMultipartFile mockMultipartFile = Mock()

    def setupSpec(){

    }

    def setup(){

    }

    def clean(){

    }

    def cleanSpec(){

    }

    def "upload file"(){
        given:
            fileService.upload(mockMultipartFile) >> true
        when:
            def result = fileService.upload(mockMultipartFile)
        then:
            result==true
    }

    def "download file if exists"(){
        given:
            fileService.downloadFile(1) >> true
        when:
            def result = fileService.downloadFile(1)
        then:
            result==true
    }
}

I would like to test method with Mock, without spring context. How should I do it ? Now, the result variable return null. I would like to set the return value of the method.

You can't annotate mocks with @Shared and there is no sense in it. @Shared is for other purposes :

Sometimes you need to share an object between feature methods. For example, the object might be very expensive to create, or you might want your feature methods to interact with each other. To achieve this, declare a @Shared field.

And further :

...mock objects should not be stored in static or @Shared fields.

Just remove @Shared and the spec will work just fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM