简体   繁体   中英

Using Post when testing with NancyFx

I have a simple object called UserDto which looks like:

public class UserDto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I have a Nancy Controller and the simplified code to create a user is, not giving the path info, because that all works:

public void Create()
{
    try
    {
        var user = this.Bind<UserDto>
        // Create user using the user return variable
    }
    catch (Exception e)
    {
    }
}

All this code works find when I test it manually, but I wanted to create some automated tests that will call the web address like I successfully do with my GET methods.

The internals of my [TestMethod] Test code looks like:

var bootstrapper = new DefaultNancyBootstrapper();
Browswer browser = new Browser(bootstrapper, to => to.Accept("application/json"));

UserDto newUser = new UserDto
{
    FirstName = "TestFirst",
    LastName = "TestLast"
};
string jsonUser = JsonConvert.SerializeObject(newUser);

var result = browser.Post("/DB/users/create, with =>
{
    with.JsonBody(jsonUser); 
         // or
    with.Body(jsonUser);
}

If I use "with.JsonBody(jsonUser), my controller code throws an exception and I end up in the catch block with the error: "Unable to bind to type UserDto"

If I use "with.Body(jsonUser), my controller code does NOT throw an error, but the resulting user object is there with all its members, but all members of the object are null. user shows FirstName & LastName, but they are both null.

I even tried using "with.Body(newUser); but got the compile time error "Cannot convert from UserDto to string".

I know the controller code works, so there has to be something wrong with my test code. I'm obviously not handing off the newUser object correctly.

Any help would be greatly appreciated.

To solve this problem, I had to use the following code in the test method:

var result = browser.Post("/DB/SQLite/users/create", with =>
{
    with.Header("Content-Type", "application/json");
    with.Body(jsonUser);
});

Therefore I was missing the header designation, which made all the difference.

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