-1

Mock object is not working when i try to access private method using reflection

Main Class:

@Component
public class ActualClass{
@Autowired 
MockClass data;
private String sampleMethod(String data){
//
List<String> list=data.getdata("something") // trying to mock this line 
//}
}

Mock Class:

@Component
public class MockClass{
public List<String> getdata(String serviceName){
return restTemplate.getForObject("http://localhost:9000/data/something", 
ArrayList.class); this line will return some datas as list}
}

My TestCase:

public class TestCases{

@Autowired 
MockClass mockobj;

@Autowired
@InjectedMocks
ActualClass actualClass

@Test
public void valid(){
MockitoAnnotations.initMocks(this);

List<String> obj=new ArrayList<String>();
obj.add("something")
when(mockobj.getdata("something")).thenreturn(obj);

Class<?> cObject=Class.forName("com.ActualClass");
ActualClass actualClass=(ActualClass) cObject.newInstance();
Method method=cObject.getDeclaredMethod("sampleMethod",String.class);
method.setAccessible(true);
method.invoke(actualClass,"date");}
}

can you anyone tell me whats going wrong in my test cases? the same mock object is working when i access public method.

i am having problem with only private method.

how can i solve this?

karthick S
  • 51
  • 1
  • 2
  • 9
  • 2
    Rather than trying to do those tricky things, [test your private method through the public methods](https://stackoverflow.com/a/1043013/545127). – Raedwald Mar 07 '19 at 12:39
  • i am doing code coverage so i need to cover all the methods. – karthick S Mar 07 '19 at 12:43
  • You still achieve that by only testing public method. If a private method would remain untested, then the method isn't called anyway and can be deleted. – Tom Mar 07 '19 at 12:47

1 Answers1

0

There are a few testing smells you should avoid.

  • You should test behaviour of your objects not their implementation details. Private methods are implementation details and as such are likely to change
  • Tests should not use reflection. Reflection depends on implementation details of your objects which makes tests fragile
  • Code coverage should not be goal of testing. When metric becomes the goal it stops being a good metric

How you should test it then?

Mock your MockClass and test through the public method. If writing such test is overly awkward, fragile or not possible you should reconsider your design.

Januson
  • 4,533
  • 34
  • 42