我正在编写一个小应用程序来自学 ASP.NET MVC,它的一个功能是能够在亚马逊(或其他网站)搜索书籍并将它们添加到“书架”。
所以我创建了一个名为 IBookSearch 的接口(使用方法 DoSearch),以及一个看起来像这样的 AmazonSearch 实现
public class AmazonSearch : IBookSearch
{
public IEnumerable<Book> DoSearch(string searchTerms)
{
var amazonResults = GetAmazonResults(searchTerms);
XNamespace ns = "http://webservices.amazon.com/AWSECommerceService/2005-10-05";
var books= from item in amazonResults.Elements(ns + "Items").Elements(ns + "Item")
select new Book
{
ASIN = GetValue(ns, item, "ASIN"),
Title = GetValue(ns, item, "Title"),
Author = GetValue(ns, item, "Author"),
DetailURL = GetValue(ns, item, "DetailPageURL")
};
return books.ToList();
}
private static XElement GetAmazonResults(string searchTerms)
{
const string AWSKey = "MY AWS KEY";
string encodedTerms = HttpUtility.UrlPathEncode(searchTerms);
string url = string.Format("<AMAZONSEARCHURL>{0}{1}",AWSKey, encodedTerms);
return XElement.Load(url);
}
private static string GetValue(XNamespace ns, XElement item, string elementName)
{
//Get values inside an XElement
}
}
理想情况下,我希望完成这种 TDD 风格,首先编写一个测试。但我必须承认我很难理解它。
我可以创建一个实现 DoSearch() 的 FakeSearch 并返回一些临时书籍,但我认为目前这不会带来任何价值,不是吗?也许稍后当我有一些使用书籍列表的代码时。
What else could I test first? The only test I can think of would be one that mocks the call to the cloud (at GetAmazonResults) and then checks that DoSearch can execute the Linq2XML select correctly and return the correct list. But it seems to me that this type of test can only be written after I have some code in place so I know what to mock.
Any advice on how you guys and girls would go around doing this test-first style?