java - Create a mock calling a constructor -


suppose have following class:

class person {   private string name;   private integer id;   public person(string name){      this.name=name;      this.id=random();   }    int random() {      return new random().nextint();   } } 

it's possible create partial mock person class calling constructor mocked random() method? mean this:

person a=easymock.createmockbuilder(person.class)                   .withconstructor(string.class)                   .withargs("albina")                   .addmockedmethod("random")                   .createmock(); 

i differently: use dependency injection "insert" random object:

public person(random rand, string name) { this.random = rand ... 

and

public person(string name) { this(new random(), name) ... 

then can create ordinary object of class; using mocked random.

very often, think "complicated" solutions somehow test our production code. wrong approach: if code hard test; change code!


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -