我想在c#中编写一个单元测试来测试那些正在进行数据库操作(2-3个数据库操作)的方法以及其他一些写在里面的逻辑它。我们如何模拟内部有很多数据库操作的方法
private static APIResponse SubmitRequest(HttpWebRequest request, string info)
{
APIResponse responseObj = new APIResponse();
WebResponse response = null;
// save the log into database.
Log.Request(request.Method + " to " + request.RequestUri.ToString() + ": " + info);
try
{
response = request.GetResponse();
}
catch (WebException e)
{
var resp = (HttpWebResponse)e.Response;
if (resp.StatusCode == HttpStatusCode.NotModified)
{
responseObj.StatusCode = HttpStatusCode.NotModified;
responseObj.Headers = resp.Headers;
eTAG = responseObj.Headers["eTag"];
// save the log into the database.
Log.Response("<empty>");
return responseObj;
}
// save the log into the database.
Log.Warning(e.Message);
response = e.Response;
}
if (response == null)
{
Log.Response("<null>");
return null;
}
StreamReader reader = new StreamReader(response.GetResponseStream());
string textResponse = reader.ReadToEnd();
HttpStatusCode status = ((HttpWebResponse)response).StatusCode;
reader.Close();
response.Close();
if (textResponse != null)
{
textResponse = textResponse.Trim();
}
// save the log into the database.
Log.Response(textResponse.Length == 0 ? "<empty>" : textResponse);
if (textResponse.Length == 0)
return null;
responseObj.Headers = response.Headers;
responseObj.Message = textResponse;
responseObj.StatusCode = status;
eTAG = responseObj.Headers["eTag"];
return responseObj;
}
正如你可以在摘要中看到,我们在代码的不同时间之间保存记录到数据库中。我们如何模拟/停止这些日志来保存。
public static void Request(string text)
{
-- code to save the code in db.
}
public static void Response(string text)
{
-- code to save the code in db.
}
我们怎么能实现呢?有人猜测任何人吗?
能如你所愿方法的代码添加到单元测试请。 – Scrobi
通常,您要提取将数据库调用为依赖项的类并通过构造函数注入。这样你就可以实例化一个测试版/模拟的类,并将其传递到你想测试的类 – Stuart
这是一个非常广泛的问题。你可以模拟数据层本身并返回虚拟数据,或者你可以模拟IQueryable(如果你使用任何),并使用例如字典而不是实际的表。如果您使用EF,则可以模拟EF上下文。您可以使用SQLite内存数据库而不是实际的数据库。 EF Core甚至只有用于测试的内存数据库 –