繁体   English   中英

如何对包含结构作为参数的方法进行单元测试?

[英]How to unit test a method that contains a struct as a parameter?

我正在为采用结构作为参数的方法编写单元测试。

我使用要在TestClass中测试的方法创建了该类的实例,但是即使在该类中将其设置为public,也无法访问其struct成员。

我错过了什么吗?

这是该类的代码:

public class Patient
{
    public struct patientInfo
    {
        public string firstName;
        public string lastName;
        public string telephoneNumber;
        public string dateOfBirth;
        public string gender;         
        public string address;
    }

 // Method I want to test:
 public bool Register(patientInfo patientDetails)
 {
      // Method code in here.
 }

测试类的代码:

[TestClass]
public class RegisterPatientTest
{       
    [TestMethod]
    public void RegisterMethodTest()
    {

        Patient TestPatient = new Patient();

        TestPatient. //Can't access the struct member...            

        // What I want to use the struct for but gives error:  
        Assert.IsTrue(TestPatient.Register(patientDetails) == false);    
    }
}

您将需要Patient.patientInfo来访问该结构。 该结构不属于您的类的特定实例。 实际上,您需要周围类的名称作为内部类的标识,就像周围类将是一个namespace 因此,要使用new Patient.patienInfo { ... }创建结构的实例。

除此之外,您可以使用Assert.IsFalse来使代码更清晰。 所以你得到这个:

[TestMethod]
public void RegisterMethodTest()
{
    var p = new Patient();

    Patient.patientInfo info;
    info.firstName = ...

    // What I want to use the struct for but gives error:  
    Assert.IsFalse(p.Register(info));    
}

但是,我完全看不到使用此嵌套结构有什么用。 您可以直接在类中拥有属性,从而使代码结构更加容易:

public class Patient
{
    public string firstName;
    public string lastName;
    public string telephoneNumber;
    public string dateOfBirth;
    public string gender;         
    public string address;
}

现在,只需在测试中调用此命令即可:

var p = new Patient { firstName = ... };
Assert.IsFalse(myPatient.Register());

您必须通过以下方式访问您的结构:

var info = new Patient.patientInfo();

该结构不是成员-它的定义只是嵌套的,因此您必须指定其包含类( Patient. )才能进行访问。

尝试以下方法:

public class Patient
{
    // Member:
    public PatientInfo Info;

    // Struct definition:
    public struct PatientInfo // Use UpperCamelCase
    {
        // ...
    }
}

现在,您可以访问您的成员:

new Patient().Info = //...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM