1

I have class like

public class Myclass{ 

public boolean processePersonData(){
private Person p;
boolean flag=true;
if(flag){
 p= new Person("john",1);
 }
  else{
 p= new Person("adam",2);
}

//do sth with p

}
}

How can I mock the variable p, I googled a lot but did not get the answer. can this be done with mockito. I dont want any changes in the code .

Ashish Banker
  • 2,243
  • 3
  • 20
  • 21

1 Answers1

10

You don't.

When Unittesting you verify public observable behavior that means: What results are returned depending on the input and how does the unit communicate with its dependencies.

The variable 'p' is an implementation detail that you do not verify. This is because in may change without changing the units behavior and you don't want to change the test in that case.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
  • but what if the variable P is an object like the JdbcTemplate that make a call to the DB. I see that extracting it out to a separate method and then spying is an option. But in order to do that, I need to change the access specifier to non-private for the extracted out method. I don't want to do that. – Andy Jan 04 '21 at 15:44
  • @Andy *"but what if the variable P is an object like the JdbcTemplate that make a call to the DB."* **---** Then (IMHO) you violate the "Separations of Concerns/Single Responsibility Pattern". You should always separate DTOs (what I'd suspect a class named `Person` to be) from code doing actual work like interacting with the database. – Timothy Truckle Jan 05 '21 at 18:50
  • I was thinking of a scenario where we have a DAO class that has a method inside which we have jdbcTemplate as a local variable. This jdbctemplate runs a query to fetch results from the DB. How to unit test this function? TIA – Andy Jan 05 '21 at 22:31
  • @Andy I'd say, that is a different question... ;o) – Timothy Truckle Jan 06 '21 at 19:14
  • @haha, I am stuck with such a scenario and wondering what to do with it. – Andy Jan 06 '21 at 23:08
  • @Andy you may find suggestione here https://stackoverflow.com/questions/15668234/mocking-datasource-for-jdbctemplate-with-mockito and here https://stackoverflow.com/questions/13818712/how-to-mock-jdbctemplate-queryforobject-method – Timothy Truckle Jan 07 '21 at 02:17