简体   繁体   English

如何在 java 中模拟 function 调用

[英]How to mock a function call in java

I am new to Unit testing and trying to figure out the different implementations of testing.我是单元测试的新手,并试图找出不同的测试实现。 I m trying to figure out how to mock a particular function call.我试图弄清楚如何模拟特定的 function 调用。 I came across Mock Spy but didn't quite understand how it's been used.我遇到了 Mock Spy,但不太了解它是如何使用的。 Can someone tell me how mocking is done in such cases...有人可以告诉我在这种情况下如何完成 mocking ......

Class ABC {
   
    void display(String name, int id){
       validateName(name);
       validateId(id);
     }
}


Class TestIt{
   
   @Test
   void testValidation(){

     //how to mock validateName function call and test only validateId ?
     ABC obj=new ABC();
     obj.display("abc",2);
   }
}

Some mocking frameworks allow partial mocks (most of the mocked class is actuall the real thing, just some methods are mocked).一些 mocking 框架允许部分模拟(大多数模拟的 class 实际上是真实的,只是模拟了一些方法)。 If your example is anywhere near the real code, I would not test the two methods separately.如果您的示例接近真实代码,我不会分别测试这两种方法。 If one of these methods do something that is not wanted in a test, like accessing an external service (DB, webservice, filesystem), the I would encapsulate that functionality into an adapater class and inject it into ABC .如果其中一种方法执行了测试中不需要的操作,例如访问外部服务(数据库、Web 服务、文件系统),我会将该功能封装到适配器 class 中并将其注入到ABC中。 Then you can mock the adapter.然后你可以模拟适配器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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