Java Mockito和代表团

Tho*_*yme 1 java delegates mockito

每次调用getLastModifiedDate时我都需要返回新的Date().我正在使用这个模拟:

when(network.getLastModifiedDateOf(any(URL.class))).
            thenReturn(formatDate(new Date()));
Run Code Online (Sandbox Code Playgroud)

但是,每次调用getLastModifiedDateOf时,它都会返回测试开始时的相同日期/时间.我想我需要像C#委托这样的东西,每次模拟被击中时调用新的Date().

Mic*_*vis 9

查看Answer回调,而不是直接返回值.

when(...).thenAnswer(new Answer() {
    Object answer(InvocationOnMock invocation) {
        return formatDate(new Date());
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在Mockito 1.9.0中,您将能够编写`when(network.getLastModifiedDateOf(any(URL.class))).then(returnFormattedDate(new Date()));``where`是`的别名thenAnswer`和`returnFormattedDate`当然是一个返回`Answer`的自定义方法. (2认同)