Greg P
Greg P

Reputation: 802

Writing Unit Tests with ODataQueryOptions

I am new to writing test cases for WebAPI's. I have seen similar questions asked in the past, but not answered, but I am wondering how I would test my APIs if they have an ODataQueryOptions as part of the parameters. See below:

public IQueryable<Item> GetByIdAndLocale(ODataQueryOptions opts, 
                                         Guid actionuniqueid, 
                                         string actionsecondaryid)

Would I have to moq this? If so, how would this look? Any help would be appreciated.

Upvotes: 5

Views: 5676

Answers (2)

zoe
zoe

Reputation: 889

For ODataQueryOptions perspective, you may want to test that all the OData query options can work with your Function. So firstly you need to create an instance of ODataQueryOptions. Here is an example:

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri);
ODataQueryContext context = new ODataQueryContext(EdmCoreModel.Instance, elementType);
ODataQueryOptions options = new ODataQueryOptions(context, request);

So you need to create your own EDM model to replace EdmCoreModel.Instance, and replace requestUri with your query. elemntType in ODataQueryContext is "The CLR type of the element of the collection being queried".

Upvotes: 7

AlanT
AlanT

Reputation: 3663

I cannot tell from the phrasing, but is the above call (GetByIdAndLocale) the Web API that you are trying to test or are you trying to test something that is calling it?

One uses a mock or a stub to replace dependencies in a Unit Under Test (UUT). If you are testing GetByIdAndLocale() then you would not mock it though if it calls something else that takes the ODataQueryOptions as a parameter, you could use Moq to stub/mock that call.

If you are testing some unit that calls GetByIdAndLocale() then, yes, you could moq it. How exactly you might do this depends upon the goal (checking that the correct values are being passed in vs. checking that the returned IQueryable is correctly processed) basically, matching against It.IsAny() or against some matcher.

Which do you want to test?
GetByIdAndLocale(), something that calls it or something (not shown) that it calls?

What are you interested in verifying?
Correct options are passed in or the processing of the return from the mocked call?

Upvotes: 0

Related Questions