java - How to design a private/final method available for mocking? -


this class have test:

public class downloader {   public string download(string uri) {     httpclient client = this.gethttpclient();     client.seturi(uri);     return client.get();   }   private httpclient gethttpclient() {     httpclient client = new httpclient();     // + config     return client;   } } 

very simple. want test behavior when gethttpclient() throws exception. however, can't mock method, since private. common practice in such situation?

i make httpclient field of class set on construction (via interface). have ability create mock httpclient can throw exception during test if want, e.g.:

public class downloader {   private ihttpclient client;    public downloader(ihttpclient client) {     this.client = client;   }    public string download(string uri) {      this.initialisehttpclient();      client.seturi(uri);      return client.get();    }     private httpclient initialisehttpclient() {      // + config    }  } 

then call constructor real httpclient in production code , mock in test code. may need create wrapper httpclient real code.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -