[英]mock object is not working while trying to access private method using reflection in junit
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?我该如何解决这个问题?
There are a few testing smells you should avoid.您应该避免一些测试气味。
How you should test it then?那你应该如何测试呢?
Mock your MockClass
and test through the public method.模拟您的MockClass
并通过公共方法进行测试。 If writing such test is overly awkward, fragile or not possible you should reconsider your design.如果编写这样的测试过于笨拙、脆弱或不可能,您应该重新考虑您的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.