Scala / Mockito:如何模拟在另一个方法中调用的方法的结果?

时间:2018-05-15 12:19:29

标签: java spring scala mockito

我正在尝试使用Mockito编写Scala单元测试,用于" doSomeBusinessLogic"在下面的类中找到的方法:

@Service
public class HotelsService {

private final HotelsServiceInt hotelsServiceInt;

public HotelsService(HotelsServiceInt hotelsServiceInt) {
  this.hotelsServiceInt = hotelsServiceInt;
}

public List<String> getHotels(long val1, long val2) {
  return hotelsServiceInt.getHotels(val1, val2)
}

public boolean doSomeBusinessLogic(long val1, long val2) {
  List<String> hotels = getHotels(val1, val2);
  // Do some logic and return true or false
}

这是界面:

public interface HotelsServiceInt {

@GET("/{val1}/{val2}")
Observable<List<String>> getHotels(
@Path("val1") long val1,                                                                             
@Path("val2") long val2);
}

这是Scala测试,我为它写道:

import org.mockito._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{BeforeAndAfter, FunSpec}
import org.mockito.Mockito._

 class Spec extends FunSpec with MockFactory with BeforeAndAfter {
   @InjectMocks
   var hotelsServiceInjectedMock: HotelsService = _
   @Mock
   var hotelsService: HotelsService = _

   before{
    hotelsServiceInjectedMock = new HotelsService(hotelsServiceInt)
       MockitoAnnotations.initMocks(this)
   }
   describe("Test") {

   it("Should return false.") {
    val val1 = 1l
    val val2 = 2l
    list = new ArrayList()
    list.add("Hitlon")
    list.add("Sheraton")
    list.add("Rotana")
    doReturn(list).when(hotelsService).getHotels(
                     Matchers.any(), Matchers.any())
    val result = hotelsServiceInjectedMock.doSomeBusinessLogic(val1, val2)
    assert(result == false)
  }}
}

但是,调试上面的测试表明实际调用List<String> hotels = getHotels(val1, val2);

有没有办法让#34; doSomeBusinessLogic&#34;代码执行,但嘲笑&#34; getHotels&#34;方法

1 个答案:

答案 0 :(得分:1)

是的,这是可以实现的,因为你有一个档案:

private final HotelsServiceInt hotelsServiceInt;

您可以在测试类中模拟hotelsServiceInt并返回模拟结果。在调用doSomeBusinessLogic之前,只需返回一个模拟列表,你就可以了。 您还需要更改@Mock@InjectMock的变量类型,如下所示:

   @Mock
   var hotelsServiceInitMock: HotelsServiceInt = _
   @InjectMocks
   var hotelsService: HotelsService = _
   //then do this:
   doReturn(list).when(hotelsServiceInitMock).getHotels(
                 Matchers.any(), Matchers.any())

现在您应该能够获得所需的结果。