简体   繁体   English

Junit 和 Mockito,在传递的参数上捕获方法调用

[英]Junit And Mockito, Capturing method call on passed argument

I am relatively new to Mockito and Junit in Java.我对 Java 中的 Mockito 和 Junit 比较陌生。 How can I capture or verify the interaction on the argument passed to function that I am testing.如何捕获或验证传递给我正在测试的 function 的参数的交互。 Ex-- Main class Ex-- 主class

public class A{

 public void setValues(Person p){
  p.setFirstName('Lucky');
  p.setLastName('Singh');

// Some more code
 }
}

Test class测试 class

class Test {

@InjectMocks
A classUnderTest;

@Test 
public void tests(){
  classUnderTest.setValues(new Person());
// What to do next to verfiy that the setFirstName and setLastName where really called on Person Object as setValues have void return type??
}
}

Now i want to test this setValues method with void return type.现在我想用 void 返回类型测试这个 setValues 方法。 I know if return type would have been Person I could have used assert.我知道如果返回类型是我可以使用断言的人。 But I cannot change method defination.但我无法更改方法定义。 So I want to verify that the call to setFirstName and setlastName is made.所以我想验证是否调用了 setFirstName 和 setlastName。
I am using pit-test and the mutation removed call to setFirstName and setlastName is not getting KILLED.我正在使用pit-test,并且突变删除了对setFirstName的调用,并且setlastName没有被杀死。
How can I achieve this??我怎样才能做到这一点?

You can inject a spy for your Person class and then verify if the methods are called as follows:您可以为您的Person class 注入一个间谍,然后验证方法是否调用如下:

class Test {
  @Spy
  Person person = new Person();

  @InjectMocks
  A classUnderTest;

  @Test 
  public void tests(){
    classUnderTest.setValues(person);

    // You can now verify if the methods setFirstName and setLastName where really called on Person
    verify(person, times(1)).setFirstName(isA(String.class));
    verify(person, times(1)).setLastName(isA(String.class));
  }
}

A spy will wrap an existing instance, in your case Person .间谍将包装现有实例,在您的情况下Person It will still behave in the same way as the normal instance, the only difference is that it will also be instrumented to track all the interactions with it so that you can actually verify on the methods that are called.它仍然会以与普通实例相同的方式运行,唯一的区别是它还将被检测为跟踪与它的所有交互,以便您可以实际验证调用的方法。

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

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