Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Forked from prabirshrestha/1 - UserModuleTest.cs
Created November 27, 2012 21:49
Show Gist options
  • Save tugberkugurlu/4157336 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/4157336 to your computer and use it in GitHub Desktop.
nancy testing example
using CsQuery;
using Nancy;
using Nancy.Testing;
using Should;
using Xunit;
public class UserModuleTest
{
[Fact]
public void WhenUserNotFound()
{
// given
var bootstrapper = new ConfigurableBootstrapper(with =>
{
with.Dependency<FakeUserService>();
with.Module<UserModule>();
});
var browser = new Browser(bootstrapper);
// when
var result = browser.Get("/user/1");
// then
result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);
}
[Fact]
public void WhenUserFound()
{
// given
var bootstrapper = new ConfigurableBootstrapper(with =>
{
with.Dependency<FakeUserService>();
with.Module<UserModule>();
});
var browser = new Browser(bootstrapper);
// when
var result = browser.Get("/user/3");
// then
result.StatusCode.ShouldEqual(HttpStatusCode.OK);
var doc = CQ.Create(result.Body.AsString());
doc.Find("#id").ToString().ShouldEqual("3");
doc.Find("#name").ToString().ShouldEqual("Prabir");
}
}
public class User
{
public long Id { get; set; }
public string Name { get; set; }
}
public interface IUserService
{
User GetUser(long userId);
}
using Dapper;
public class SqlUserService : IUserService
{
private readonly string connectionString;
public SqlUserService()
: this(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString)
{
}
public SqlUserService(string connectionString)
{
this.connectionString = connectionString;
}
public User GetUser(long userId)
{
using (var cn = new SqlConnection(this.connectionString))
{
const string sql = @"select * from user where id=@id";
cn.Open();
return cn.Query<User>(sql, new { id = userId }).SingleOrDefault();
}
}
}
public class FakeUserService : IUserService
{
public User GetUser(long userId)
{
if (userId == 3)
return new User { Id = 3, Name = "Prabir" };
return null;
}
}
public class UserModule : NancyModule
{
public UserModule(IUserService userService)
: base("/user")
{
Get["/{userId}"] =
x =>
{
long userId = x.userId;
var user = userService.GetUser(userId);
if (user == null)
return 404;
return View["user", user];
};
}
}
@model User
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>sample nancyfx</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>
Id: <b id="userId">@Model.Id</b><br/>
Name: <b id="name">@Model.Name</b>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment