0

尝试对访问实体框架的函数进行单元测试。所以我尝试将所有实体代码放入下面的测试函数中?然而它在 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");
        }


    }
4

2 回答 2

2

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

上下文的初始化应该在您的 StegApp()内部完成,或者您应该能够从不同的范围将上下文传递给您的 StegApp()。根据我对您的代码的阅读,您的 StegApp() 将无法访问您创建的 dataContext 变量。

您对空用户的测试已经在 AuthenticateCredentials() 方法下的 RetrieveKeyFn() 内进行,因此不需要第一个“Assert.IsNotNull(user)”。我建议您将 RetrieveKeyFn 的业务逻辑与您的 UI 行为分开,以便您可以轻松地进行单元测试。您可以将“消息框”操作绑定到一个按钮单击事件处理程序,该处理程序仅调用 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);
    }
于 2013-01-21T07:34:36.630 回答
0

我的单元测试工作正常。我的错误是没有将 app.config 文件复制到测试项目中!虽然老实说,我希望 Visual Studio 无论如何都会这样做。

于 2013-01-25T15:14:35.800 回答