我已經使用上了班的倉庫構造方法注入,我已經注意到了以下工作:依賴注入 - 將客戶對象造成測試失敗
public CreateInvoiceResult CreateInvoice(string Code, int qty, string Name)
{
if (string.IsNullOrEmpty(Code) || qty <= 0 || repository.GetByName(Name).ID <= 0)
{
return new CreateInvoiceResult(false);
}
但是改變如下代碼(在加入「客戶卡斯特')導致測試失敗?
public CreateInvoiceResult CreateInvoice(string stockCode, int quantity, string customerName)
{
Customer cust = repository.GetByName(Name);
if (string.IsNullOrEmpty(Code) || qty <= 0 || cust.ID <= 0)
{
return new CreateInvoiceResult(false);
}
試驗例:
請你能解釋一下爲什麼發生這種情況,我該如何改正?
編輯:更新了使用起訂量,使用正確的資料庫測試:
[TestClass]
public class MockCustomerRepositoryDBTests
{
public MockCustomerRepositoryDBTests()
{
IList<Customer> customers = new List<Customer>
{
new Customer { ID = 1, Name = "Jim Smith",
Address = "14 Main Road"},
new Customer { ID = 2, Name = "Alex Smith",
Address = "78 Avanue"},
new Customer { ID = 3, Name = "Paul Brown",
Address = "1 Main Road"}
};
// Mock the CustomerRepositoryDB Repository using Moq
Mock<ICustomerRepository> mockCustomerRepository = new Mock<ICustomerRepository>();
// Return a customer by Name
mockCustomerRepository.Setup(mr => mr.GetByName(
It.IsAny<string>())).Returns((string s) => customers.Where(
x => x.Name == s).Single());
// Complete the setup of the Mock Customer Repository
this.MockCustomerRepository = mockCustomerRepository.Object;
}
public readonly ICustomerRepository MockCustomerRepository;
[TestMethod]
public void stockCodeIsNullOrEmpty()
{
//Arrange
var x = new InvoiceController(MockCustomerRepository);
//Act
bool result = x.CreateInvoice("", 1, "test").Success;
//Assert
Assert.AreEqual(result, false);
}
走走System.InvalidOperationException:序列不包含任何元素'
你應該問一個關於你的moq的單獨問題。 –
無需刪除所有原始問題:)。我會放回去。 –