Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to Xunit test REST API and HttpBadRequest / HttpNotFound ?

$
0
0

At the moment I have a mock db in memory and doing sth like :

var result = _controller.GetMyStuff(1) as ObjectResult;
var oneItem = result.Value as OneThing;

Assert.Equal(200, result.StatusCode);
Assert.Equal("Thing1", oneItem.name);

how should I handle exceptions ? for example if my controller returns "  return HttpBadRequest(); " how do i test this? 

var invresult = _controller.GetMyStuff(100000) as ObjectResult;

Assert.Equal(200, invresult.StatusCode); => does not work, the object is null. Exception raised

note that I would not expect 200 here but soem other code.. 404 etc..

Also I got my REST api generated and was surprised to see the generted getXXX not using try catch around for example

_context.MyStuff.Single()

for example a call for a MySuff object with a non existing id will return an exception. That should return HttpBadRequest or HttpNotFound afaik.

Thanks for you lights in advance


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>