简体   繁体   English

如何对作为 Mockito 中的构建器类的方法参数进行单元测试?

[英]How to Unit Test A Method Argument which is a Builder Class in Mockito?

I have a dependency in the Spring Boot which is called from my class.我在 Spring Boot 中有一个依赖项,它是从我的类中调用的。 This dependency makes a call with a newly instantiated builder pattern class as an argument.此依赖项使用新实例化的构建器模式类作为参数进行调用。 I need to know if it is possible to verify if this single builder class was constructed with certain values when the dependency call is made, eg:我需要知道是否有可能在进行依赖调用时验证这个单个构建器类是否是用某些值构造的,例如:

public class MyClass {

  @Autowired
  private MyDep myDep;

  public void callMyDepService() {
    myDep.serviceCall(new MyBuilder().paramOne("One").paramTwo("Two").build());
  }

}

As you can see, a new MyBuilder is instantiated every time, so I can't just use Mockito's eq() to match the arguments' value.如您所见,每次都会实例化一个新的MyBuilder ,所以我不能只使用 Mockito 的eq()来匹配参数的值。

I would like to make sure callMyDepService calls myDep.serviceCall with certain parameter values.我想确保 callMyDepService 使用某些参数值调用 myDep.serviceCall。

Using a captor seems to be the easiest way to do that.使用俘虏似乎是最简单的方法。 Something like this, where SomeClass is the class your MyBuilder builds.像这样,其中SomeClass是您的MyBuilder构建的类。

@ExtendWith(MockitoExtension.class)
public class CaptureTest {

    @InjectMocks
    MyClass classUnderTest;

    @Mock
    MyDep myDep;

    @Test
    public void test() {

        classUnderTest.callMyDepService();

        Captor<SomeClass> captor = ArgumentCaptor.forClass(SomeClass.class);
        Mockito.verify(myDep).serviceCall(captor.capture());

        SomeClass parameter = captor.getValue();
        // do assertions
    }
}

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

相关问题 如何使用Mockito对依赖equals()的抽象类方法进行单元测试? - How to unit test an abstract class method that depends on equals() with Mockito? Mockito:如何替换被测试类调用的类方法? - Mockito: How to replace method of class which is invoked by class under test? Mockito:如何单元测试void方法Java Mockito? - Mockito: How do unit test void method java mockito? 如何对接受长字符串参数的解析方法进行单元测试 - how to unit test a parse method which is accepting a long string argument 如何为使用未知参数调用另一个方法的方法编写 Mockito 测试? - How to write a Mockito test for a method which calls another method with an unknown argument? 如何对在其builder()方法中使用静态单例工厂的构建器进行单元测试? - How to unit test a builder which uses a static singleton factory in its builder() method? Mockito - 如果参数设置在另一个 function 调用的 function 中,如何进行单元测试 - Mockito - how to unit test if argument is set in a function called by another function 使用Mockito测试void方法的参数 - Test argument of a void method with Mockito 如何使用Java Mockito 1.10.19测试构建器方法 - How can I test a builder method using Java Mockito 1.10.19 如何使用Mockito在Service类中测试void方法? - How test a void method into Service class, with Mockito?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM