如何测试方法返回的对象?
我已经开始练习 TDD 方法。我对单元测试还很陌生。
我想知道如何测试方法返回的某些对象?
例如,如果我有以下类(请原谅我的公共变量)
class Person {
public String firstName;
public String lastName;
public int age;
private void getFirstAndLastName(fullName) {
// some logic to split name into first name and last name
// and then assign first name and last name to data members
}
public Person(String fullName) {
getFirstAndLastName(fullName);
}
}
和人员创建者类,
public class PersonBuilder {
public static Person buildPerson(String fullName) {
return new Person("Sachin Tendulkar");
}
}
我想测试 PersonBuilder
类的 buildPerson()
方法的输出。 如果我想确保 buildPerson()
方法返回的对象的 firsName 是“Sachin”,lastName 是“Tendulkar”,那么我应该如何为此编写测试代码?
我应该像 object.FirstName.equals("Sachin")
一样手动检查 Person 类的成员变量还是有其他更好的方法在这种情况下进行测试? 什么
测试它的标准方法是
?顺便说一句,我正在使用 Java 和 JUnit。
请赐教!!!
I have started practicing TDD approach. I am pretty much new to unit testing.
I would like to know how to test some object returned by an method?
for example if I have following classes (please forgive me for public variables)
class Person {
public String firstName;
public String lastName;
public int age;
private void getFirstAndLastName(fullName) {
// some logic to split name into first name and last name
// and then assign first name and last name to data members
}
public Person(String fullName) {
getFirstAndLastName(fullName);
}
}
and person creator class
public class PersonBuilder {
public static Person buildPerson(String fullName) {
return new Person("Sachin Tendulkar");
}
}
I want to test the output of buildPerson()
method of PersonBuilder
class.
If I want to make sure that the firsName of object returned by buildPerson()
method is 'Sachin' and lastName is 'Tendulkar' then how should I write test code for this?
Should I check member variables of Person class manually like object.FirstName.equals("Sachin")
or is there any other better way to test in this kind of situation? What
is the standard way to test it?
and by the way, I am using Java and JUnit.
Please enlighten !!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,在您的情况下,您将检查成员变量。
但你确实应该使用属性而不是公共变量。然后你会检查属性。
Yes, in your case you would check the member variables.
But you really should use properties instead of public variables. You would check the properties then.