简体   繁体   中英

What is the correct way to create a stub/mock for the Scheme property present under Uri in Rhinomocks

I'm writing a Unit Test case for ac# method with the help of Rhinomocks framework. Inside my actual method I access the Scheme property from the Uri property present under System.Net.Http.HttpRequestMessage namespace.

The scheme property is accessed like _requestContext.RequestMessage.RequestUri.Scheme in the actual method.

When I run my unit test case, it crashes inside my actual impletementation method when it tries to access/read the scheme property.

In order to mock the URI and Scheme properties I tried like the below ways but it doesn't work as expected.

var uri = new Uri("http://tempuri.org/");
//requestContext.Expect(r => r.RequestMessage.RequestUri).Return(uri).Repeat.Any();

requestContext.Stub(x => x.RequestMessage.RequestUri).Return(uri);

requestContext.Stub(x => x.RequestMessage.RequestUri.Scheme).Return("http");//this is the value the scheme should return when it is accessed inside the actual method

What is the correct way to create a stub/mock for the Scheme property present under Uri.

Note: I'm referring to the Uri property under System.Net.Http.HttpRequestMessage namespace.

The concrete Uri used in your example will include the scheme. No need to mock it further.

var uri = new Uri("http://tempuri.org/");

var scheme = uri.Scheme; //return "http"    

requestContext.Stub(x => x.RequestMessage.RequestUri).Return(uri);

So calling RequestMessage.RequestUri.Scheme will return the scheme from the concrete Uri . Which in this case would be http , as you already know and stated in your original post.

Also based on your comment to my original suggestion, then I suggest you create an actual HttpRequestMessage and populate it as needed.

var uri = new Uri("http://tempuri.org/");
var request = new HttpRequestMessage(HttpMethod.Get, uri);

requestContext.Stub(x => x.RequestMessage).Return(request);

Now there is no need to mock anything else related to the request as the actual implementation is used.

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