更新我們的AddItemCommand多增加一個SessionId欄位用於配置GUID唯一識別
public class AddItemCommand
{
public int ProductId { get; set; }
public Guid? SessionId { get; set; }
}
新增一個AddItemResult的DTO
public class AddItemResult
{
public Guid SessionId { get; set; }
}
調整CartService封裝的AddItem改為具有返回值型態為AddItemResult
public AddItemResult AddItem(AddItemCommand command)
{
// if sessionId is provided, look it up
// add item to the existing cart
// return existing cart sessionId
ShoppingCart cart;
if (command.SessionId.HasValue)
{
cart = dbContext.ShoppingCart.SingleOrDefault(x => x.SessionId == command.SessionId);
} else
{
Guid newCartSessionId = Guid.NewGuid();
cart = new ShoppingCart { SessionId = newCartSessionId, CreatedOn = DateTime.Now };
dbContext.ShoppingCart.Add(cart);
}
cart.Items.Add(new CartLineItem { ProductId = command.ProductId, Quantity = 1 });
dbContext.SaveChanges();
return new AddItemResult { SessionId = cart.SessionId };
}
}
微調CartController的AddItem方法
[HttpPost]
public IActionResult AddItem(AddItemCommand command)
{
var result = cartService.AddItem(command);
return Ok(result);
}
這裡使用XUnit (跟其他兩牌用法其實差異不大)
相應比較對照表
在此會採用到UseInMemoryDatabase記憶體中產生一個暫時性DB用於for單元測試進行臨時性的驗證
單元測試要求的重點
不和外部資源(DB,WebService,web api,檔案系統…)相關聯,通常
又被稱作「隔離測試」(Ex:即便在離線環境也要能夠測試跟api呼叫或DB存取有關的unit test)
Install-Package Microsoft.EntityFrameworkCore.InMemory -Version 3.1.5
public class AddItemToCartShould
{
private DbContextOptions<StoreContext> options;
public AddItemToCartShould()
{
options = new DbContextOptionsBuilder<StoreContext>()
.UseInMemoryDatabase(databaseName: "Cart")
.Options;
}
[Fact]
public void CreateCartIfNotFound()
{
using (var context = new StoreContext(options))
{
var cartService = new CartService(context);
var result = cartService.AddItem(new AddItemCommand { ProductId = 1, SessionId = null });
Assert.NotEqual(Guid.Empty, result.SessionId);
}
}
[Fact]
public void NotCreateCartIfExistingOneFound()
{
Guid sessionId = Guid.NewGuid();
using (var context = new StoreContext(options))
{
context.ShoppingCart.Add(new ShoppingCart { SessionId = sessionId });
context.SaveChanges();
}
using (var context = new StoreContext(options))
{
var cartService = new CartService(context);
var result = cartService.AddItem(new AddItemCommand { ProductId = 1, SessionId = sessionId });
Assert.Equal(sessionId, result.SessionId);
}
}
}
再次我們要進行的驗證就是確保session每一次只獲取一個購物車