我有一个带签名的服务类和方法:
@Service
public class FileService {
....
....
public Optional<FileDescr> upload(MultipartFile uploadFile){...}
public Resource downloadFile(int linkID){...}
}
和测试文件(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
}
}
我想用Mock测试方法,没有spring上下文。我该怎么办?现在,result
变量返回null。我想设置方法的返回值。
你不能用@Shared
注释模拟,没有任何意义。 @Shared is for other purposes:
有时您需要在要素方法之间共享对象。例如,创建对象可能非常昂贵,或者您可能希望您的要素方法相互交互。要实现此目的,请声明一个@Shared字段。
和further:
...模拟对象不应存储在静态或@Shared字段中。
只需删除@Shared
,规格就可以了