Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to mock Response without executing a request? #245

Closed
smiklosovic opened this issue Jun 5, 2019 · 6 comments
Closed

How to mock Response without executing a request? #245

smiklosovic opened this issue Jun 5, 2019 · 6 comments
Assignees

Comments

@smiklosovic
Copy link

Hey,

I want to test my unmarshalling logic and I do not want to make a call to server, I just want to pretend I already got some response. body is package private in Response so how should I set that one?

@jeevatkm
Copy link
Member

jeevatkm commented Jun 9, 2019

@smiklosovic you could use any http mocking library with Resty to mock request. for e.g. readme reference

@jeevatkm jeevatkm self-assigned this Jun 9, 2019
@jeevatkm
Copy link
Member

I'm closing this one.

@smiklosovic
Copy link
Author

smiklosovic commented Jun 12, 2019

@jeevatkm no worries, I did this for reference

client.testResponse = &resty.Response{
        RawResponse: &http.Response{
            Body:       ioutil.NopCloser(bytes.NewReader([]byte(`{ "my": "json"}`))),
            Status:     "200 OK",
            StatusCode: 200,
    },
}

Then I have some logic around that in my client ..

@Kolyunya
Copy link

Kolyunya commented Sep 25, 2023

@smiklosovic when you set a http.Response as a RawResponse, it wouldn't be taken into account e.g. by resty.Response.String().

This quirk makes resty.Response untestable... Illustration:

package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/go-resty/resty/v2"
)

func mockResponse(status int, body string) *resty.Response {
	rawResponse := new(http.Response)
	rawResponse.StatusCode = status
	rawResponse.Body = io.NopCloser(strings.NewReader(body))

	response := new(resty.Response)
	response.RawResponse = rawResponse

	return response
}

func main() {
	response := mockResponse(200, "body")
	body := response.String()

	fmt.Printf("Response body is: %v\n", body)
}

Have you managed to work around this somehow?

@jeevatkm
Copy link
Member

jeevatkm commented Oct 8, 2023

@Kolyunya @smiklosovic I have added Response.SetBody(b []byte) will be released in v2.10.0. I should have done it earlier.
Currently, it's available in v2.10.0-rc.2.

@Kolyunya
Copy link

Kolyunya commented Oct 8, 2023

@jeevatkm thanks for a quick fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

3 participants