Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 创建一个调用构造函数的模拟_Java_Unit Testing_Easymock - Fatal编程技术网

Java 创建一个调用构造函数的模拟

Java 创建一个调用构造函数的模拟,java,unit-testing,easymock,Java,Unit Testing,Easymock,假设我有以下课程: class Person { private String name; private Integer id; public Person(String name){ this.name=name; this.id=random(); } int random() { return new Random().nextInt(); } } 通过使用mockedrandom()方法调用构造函数,可以为Person类创建部分

假设我有以下课程:

class Person {
  private String name;
  private Integer id;
  public Person(String name){
     this.name=name;
     this.id=random();
  }

  int random() {
     return new Random().nextInt();
  }
}
通过使用mocked
random()
方法调用构造函数,可以为
Person
类创建部分模拟? 我的意思是这样的:

Person a=EasyMock.createMockBuilder(Person.class)
                  .withConstructor(String.class)
                  .withArgs("Albina")
                  .addMockedMethod("random")
                  .createMock();

我会采取不同的做法:使用依赖项注入来“插入”随机对象:

public Person(Random rand, String name) { this.random = rand ...

然后可以创建类的普通对象;这将使用一个模拟的随机变量


通常,我们会考虑“复杂”的解决方案来测试我们的产品代码。但这是错误的方法:如果你的代码很难测试;然后更改您的代码

多谢各位。有一些解决办法。
public Person(String name) { this(new Random(), name) ...