Java 在JUnit中模拟方法时传递对象

Java 在JUnit中模拟方法时传递对象,java,junit,mockito,Java,Junit,Mockito,我正在为以下方法编写单元测试: public void myMethod(){ String url = "post url"; HttpHeaders httpHeaders = new HttpHeaders(); //adding attributes to httpHeaders object ServiceCallDto serviceCallDto = new ServiceCallDto(); //adding attribut

我正在为以下方法编写单元测试:

public void myMethod(){
   String url = "post url";

   HttpHeaders httpHeaders = new HttpHeaders();
   //adding attributes to httpHeaders object

   ServiceCallDto serviceCallDto = new ServiceCallDto();
   //adding attributes to serviceCallDto object for 1st call

   String body1 = httpService.post(url, httpHeaders, serviceCallDto);

   serviceCallDto = new ServiceCallDto();
   //adding attributes to serviceCallDto object for 2nd call

   String body2 = httpService.post(url, httpHeaders, serviceCallDto);

}
这里是我试图模仿的方法

public void myMethod(){
   ServiceCallDto serviceCallDto = new ServiceCallDto();
   //adding attributes to serviceCallDto object for 1st call
   when(httpService.post(anyString(), any(HttpHeaders.class), eq(serviceCall)))
    .thenReturn("Resopnse String"));
   
   serviceCallDto = new ServiceCallDto();
   //adding attributes to serviceCallDto object for 2nd call
   when(httpService.post(anyString(), any(HttpHeaders.class), eq(serviceCall)))
    .thenReturn("Resopnse String"));
但是我的方法在调用post方法后返回空值,我相信原因是我在这里使用serviceCallDto对象,它是在我的测试方法中创建的


有其他方法吗?

您能分享一下如何调用post调用吗?String response=httpService.post(url、httpHeaders、serviceCall);如果您展示了整个实现类和整个测试类,则更有可能得到答案。编辑您的问题以包含此信息,而不是代码片段。很可能,您的ServiceCall对象不相等。您是否正确实现了
equals
?您需要equals方法或参数匹配器。