I am writing a unit test for a method that takes a struct as a parameter.
I created an instance of the class with the method I want to test in the TestClass but I cannot access its struct member even though it is set as public in the class.
Am I missing something or is this not possible?
Here is the code for the class:
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.
}
Code for the test class:
[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);
}
}
You´ll need Patient.patientInfo
to access the struct. The struct doesn´t belong to a specific instance of your class. In fact you need the name of the surrounding class as identier for your inner one, as if your surrounding class would be a namespace
. So to create an instance of your struct use new Patient.patienInfo { ... }
.
Apart from this you can use the Assert.IsFalse
which makes your code clearer. So you get this:
[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));
}
However I can´t see any use of having this nested struct at all. You can have the properties directly in your class making your code-structure far easier:
public class Patient
{
public string firstName;
public string lastName;
public string telephoneNumber;
public string dateOfBirth;
public string gender;
public string address;
}
Now simply call this in your test:
var p = new Patient { firstName = ... };
Assert.IsFalse(myPatient.Register());
You have to access your struct this way:
var info = new Patient.patientInfo();
This struct is not a member -- its definition is just nested, so you have to specify its containing class ( Patient.
) to get access.
Try this instead:
public class Patient
{
// Member:
public PatientInfo Info;
// Struct definition:
public struct PatientInfo // Use UpperCamelCase
{
// ...
}
}
Now you can access your member:
new Patient().Info = //...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.