简体   繁体   English

尝试使用 junit 中的反射访问私有方法时,模拟对象不起作用

[英]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.您应该避免一些测试气味。

  • 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.模拟您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM