Here is my first class where the constructor has an object calling methods in other class.
Class Search{
public Search(String username, JSONObject accounts) throws Exception {
Credentials credentials = new Credentials(username);
String Uid = credentials.getUserName();
String Pwd = new String(credentials.getCredentials().getPassword());
}
public getDOB(){
--------------------
-------------
}
}
Class Credentaials:
import javax.resource.spi.security.PasswordCredential;
Public class Credentials{
public Credentials(String name){
}
public PasswordCredential getCredentials(){
return passwordCredential;
}
public String getUserName(){
PasswordCredential localCredential = getCredentials();
return localCredential.getUsername();
}
}
Class test:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Search.class, Credentials.class})
public class JunitTest {
@Test
public void playTest() {
PasswordCredential pwdCreds = new PasswordCredential();
pwdCreds.setPassword("test");
Credentials credentials = new Credentials("user");
Credentials credentials = Mockito.spy(credentials);
Mockito.doReturn(pwdCreds).when(credentials).getCredentials();
Mockito.doReturn("cmApptest").when(credentials).getUserName();
Search search = new Search("username", jsonobject);
search.getDOB();
}
}
Whenever I debug the test class, it is executing the getCredentials
and getUserName
methods even after I mocked them. I was expecting the actual methods not to execute, instead it should return the values as I mentioned in the JunitTest class.