我用Jodd来提出请求。是否有任何方法来创建模拟,以便在单元测试期间不会发生请求?我已经尝试过创建一个send()方法的模拟,但没有成功。
@Service
class ValidateUrlService {
val TIMEOUT = 5000
fun validateUrl(url: String): RequestVO {
var response = HttpResponse()
var timeBefore = Date()
return try{
response = HttpRequest
.post(url)
.timeout(TIMEOUT)
.connectionTimeout(TIMEOUT)
.send()
val httpStatus = response.statusCode()
buildResponseDTO(httpStatusToBoolean(httpStatus), httpStatus)
} catch (ex: Exception) {
genericExceptionHandler(ex, response.statusCode(), timeBefore)
}
}我的测验
internal class ValidateUrlServiceTest{
private val service = ValidateUrlService()
@Mock
var request: HttpRequest = HttpRequest.post(ArgumentMatchers.anyString())
@Test
fun test(){
Mockito.`when`(request.send()).thenReturn(HttpResponse().statusCode(555))
service.validateUrl("https://www.example.com")
}
}错误:
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
verify(mock).someMethod(contains("foo"))发布于 2022-02-28 14:46:56
模拟只适用于注入的对象。对于在方法作用域中创建的对象,模拟不起作用
您可以将HTTP调用抽象出一个不同的类
class HttpService {
fun post(url: String, timeOut: Long): HttpResponse {
return HttpRequest
.post(url)
.timeout(timeOut)
.connectionTimeout(timeOut)
.send()
}
}
class ValidateUrlService {
val httpService: HttpService
val TIMEOUT = 5000
fun validateUrl(url: String): RequestVO {
var response = HttpResponse()
var timeBefore = Date()
return try{
response = httpService.post(url, TIMEOUT)
val httpStatus = response.statusCode()
buildResponseDTO(httpStatusToBoolean(httpStatus), httpStatus)
} catch (ex: Exception) {
genericExceptionHandler(ex, response.statusCode(), timeBefore)
}
}现在您应该能够模拟HttpService post方法了。
发布于 2022-02-28 16:03:05
你的第一个错误在这里
@Mock
var request: HttpRequest = HttpRequest.post(ArgumentMatchers.anyString())因为您正在分配请求非模拟对象。
如果您想使用注释,您必须像这样编写测试:(我假设您使用的是JUnit5)
@ExtendWith(MockitoExtension::class)
internal class ValidateUrlServiceTest{
private val service = ValidateUrlService()
@Mock
lateinit var request: HttpRequest
@Test
fun test(){
Mockito.`when`(request.send()).thenReturn(HttpResponse().statusCode(555))
service.validateUrl("https://www.example.com")
}
}第二个问题是,您正在尝试模拟正在测试的方法中创建的对象。
您必须通过依赖项注入提供HttpRequest实例(可能使用注入的提供者作为ValidateUrlService的构造函数参数)
小贴士:如果你想避免“丑陋”的语法Mockito.`when`,你可以使用莫基托科特林图书馆或莫克库,它们都用一种更流畅的kotlin方式来编写测试。
https://stackoverflow.com/questions/71287988
复制相似问题