访问实体数据库的单元测试功能

本文关键字:单元测试 功能 数据库 实体 访问 | 更新日期: 2023-09-27 17:55:04

尝试单元测试访问实体框架的函数。所以我试图把所有的实体代码到下面的测试函数?然而,它停在Linq语句;显然,试图访问数据库对它来说太戏剧化了。也许一个解决办法是在基于sql lite或compact的单元测试函数中创建一个副本数据库;(无论如何,它不是一个大数据库)然后执行将不必离开测试函数?这是可能的,我将如何实现它?

public void RetreiveKeyFnTest()
    {
        StegApp target = new StegApp(); // TODO: Initialize to an appropriate value
        string username = "david"; // TODO: Initialize to an appropriate value
        string password = "david1"; // TODO: Initialize to an appropriate value
        string ConnectionString = ConfigurationManager.ConnectionStrings["DatabaseEntities"].ToString();
        var dataContext = new DatabaseEntities(ConnectionString);
        var user = dataContext.Users.FirstOrDefault(u => u.Username.Equals(username) && u.Password.Equals(password));
        Assert.IsNotNull(user);
        //target.RetreiveKeyFn(username, password);
        //Assert.IsInstanceOfType(target.RetreiveLogs,typeof(DataAccess));
        //Assert.IsInstanceOfType(target.p);
        //Assert.IsNotNull(target.RetreiveLogs.AuthenitcateCredentials(username,password));
        //Assert.Inconclusive("A method that does not return a value cannot be verified.");
    }

下面是我要测试的代码:

public void RetreiveKeyFn(string username, string password)
    {
        BusinessObjects.User p = RetreiveLogs.AuthenitcateCredentials(username,password);
        if (p != null)
        {
            if (RetreiveLogs.RetreiveMessages(p.UserId) == null)
            {
                DisplayLogs.Text = "Sorry No messages for you recorded in Database, your correspondant might have chose not to record the entry";
            }
            else
            {
                MessageBox.Show("LogId = " + RetreiveLogs.RetreiveMessages(p.UserId).LogId + "'n" +
                "UserId = " + RetreiveLogs.RetreiveMessages(p.UserId).UserId + "'n" +
                "Message Key = " + RetreiveLogs.RetreiveMessages(p.UserId).MessageKey + "'n" + "PictureId = " + RetreiveLogs.RetreiveMessages(p.UserId).PictureId +
                " Date & time = " + RetreiveLogs.RetreiveMessages(p.UserId).SentDateTime);
                DisplayLogs.Visible = true;
            }
        }
        else
        {
            MessageBox.Show("Please enter your correct username and password in order to retreive either key, image or both from Databse");
        }

    }

访问实体数据库的单元测试功能

首先,您应该能够在测试应用程序中访问与主/实际应用程序中使用的数据库相同的数据库。你只需要确保你的Test项目在它自己的App.config中包含你的连接字符串。

上下文的初始化应该在 StegApp()中的中完成,或者您应该能够从不同的作用域将上下文传递给StegApp()。从我读到的代码,您的StegApp()将无法访问您创建的dataContext变量。

您对空用户的测试已经发生在authenticatecredals()方法下的RetrieveKeyFn()中,因此不需要第一个"Assert.IsNotNull(user)"。我建议将RetrieveKeyFn的业务逻辑从UI行为中分离出来,这样就可以轻松地进行单元测试。您可以将"Messagebox"操作绑定为按钮单击事件处理程序,该处理程序只调用RetrieveKeyFn()。我建议这样写:

public class StegApp
{
      public DatabaseEntities context;
      //other properties
      public StegApp()
      {
           //assuming your DatabaseEntities class inherits from DbContext. 
           //You should create other constructors that allow you to set options
           //like lazy loading and mappings
           this.context = new DatabaseEntities(); 
      } 
      //ASSUMING YOUR RetrieveLogs.RetrieveMessages() function returns 
      //a Message object. replace this type with whatever type the
      //RetrieveLogs.RetrieveMessages() method returns.
      public Message RetrieveKeyFn (string username, string password)
      {
          BusinessObjects.User p = RetreiveLogs.AuthenitcateCredentials(username,password);
          if (p != null)
          {
              var message = RetrieveLogs.RetrieveMessages(p.UserId);
              if (message == null)
                  // handle behavior for no messages. In this case 
                  // I will just create a new Message object with a -1 LogId
                  return new Message {LogId =-1};
              else
                  return message;
          }
          else
              //handle behavior when the user is not authenticated. 
              //In this case I throw an exception
              throw new Exception();
      }
     //on your button click handler, do something like:
     // try 
     // {
     //     var message = RetrieveKeyFn(txtUsername.Text.Trim(), txtPassword.Text.Trim());
     //     if (message.LogId == -1)
     //         DisplayLogs.Text = "Sorry No messages for you recorded in Database, your correspondant might have chose not to record the entry";
     //     else
     //     {
     //         MessageBox.Show("Log Id = " + message.LogId)
     //         etc. etc. etc.
     //     }
     // }
     // catch
     // {
     //       MessageBox.Show ("user is not authenticated");
     // }
}

当你做单元测试时,记住在你的测试项目的App.Config中有适当的配置字符串。如果App.Config还不存在,继续创建一个。您应该为所有可能性(即1)用户有效,您收到消息,2)用户有效,没有消息,3)用户无效)创建测试。

下面是案例2

的例子
    [TestMethod]
    public void RetrieveKeyFnTest1()
    {
        StegApp target = new StegApp(); // this creates your context. I'm assuming it also creates your RetrieveLogs object, etc
        var username = "UserWithNotMessages"; //this user should exist in your database but should not have any messages. You could insert this user as part of your TestInitialize method
        var password = "UserWithNotMessagesPassword"; //this should be the proper password
        var message = target.RetrieveKeyFn(username, password);
        Assert.AreEqual (-1, message.LogId);
    }

我的单元测试工作得很好。我的错误是没有将app.config文件复制到测试项目中!虽然老实说,我希望Visual studio无论如何都能做到这一点。