我有一个简单的文档管理器,它在asp.net c#MVC项目中注入我的控制器.该项目是数据库优先的,Document表由documentId一个自动递增的整数索引.
我一直在尝试编写一个测试以测试以下实现的测试CreateNewDocument,在成功添加文档之后查找它并返回新的文档ID.
问题是我无法找到一种方法来模拟MyEntityFrameWorkEntities我可以添加文档然后使用linq搜索该文档.我认为它不起作用,因为嘲笑_context.Document.Add并没有真正做任何事情.
我的问题是这样的:我需要改变我的DocumentManager,这样的代码是可测试(例如通过更换.First用.FirstOrDefault和显示,如果返回null函数返回零),或可我(我应该)设置我的嘲笑不同,所以我能保持DocumentManager原样并写一个通过的测试?
public class DocumentManager : IDocumentManager
{
private readonly MyEntityFrameWorkEntities _context;
public DocumentManager(MyEntityFrameWorkEntities context)
{
_context = context;
}
public int CreateNewDocument(int userId)
{
var newDocumentGuid = Guid.NewGuid();
var newDocument = new Document
{
UserId = userId,
DateCreated = DateTime.Now,
DocumentGuid = newDocumentGuid
};
_context.Document.Add(newDocument);
_context.SaveChanges();
// the .First here doesn't return anything when called from tests
return …Run Code Online (Sandbox Code Playgroud) c# model-view-controller unit-testing entity-framework mocking
我遇到过这段代码,看起来原始开发人员试图使用静态字符串来缓存静态类中的值。
public static class GetStringFromSomeProcess
{
private static string theAnswer;
public static string GetString
{
get
{
if(theAnswer == null)
{
theAnswer = GoGetTheAnswerFromALongRunningProcess();
}
return theAnswer;
}
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,这是行不通的,因为您无法实例化GetStringFromSomeProcess该类,GoGetTheAnswerFromALongRunningProcess每次使用时都会被调用GetString。我错过了什么吗?