java - 如何在同一方法中模拟第二个对象?

标签 java unit-testing junit mocking mockito

现在我有一种使用 Mockito 进行测试的方法。不过方法有点复杂。在同样的方法中,我需要新建两个相同类型的对象。

Timestamp beginTimestamp = new Timestamp(Long.parseLong(beginTimeLong));
Timestamp endTimestamp = new Timestamp(System.currentTimeMillis());

我想模拟第二个对象 endTimestamp 来抛出 Exception ,但我无法避免 beginTimestamp 的影响。现在我的问题是如何仅模拟第二个对象 endTimeStamp ,并使其在调用 endTimestamp 的某些方法时抛出异常,例如:

endTimestamp.getTime()

我尝试编写如下所示的测试代码,

@Ignore
public void getSynPotentialShopBeginTimeAndEndTest4() throws Exception {
    Timestamp beginTimestamp = PowerMockito.mock(Timestamp.class);
    Timestamp endTimestamp = PowerMockito.mock(Timestamp.class);
    PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp).thenReturn(endTimestamp);

    when(endTimestamp.getTime()).thenThrow(RuntimeException.class);
    redisService.getSynPotentialShopBeginTimeAndEnd();
}

这也不起作用。这些代码没有任何红色波浪下划线,但是当我尝试运行它时,出现了如下异常:

 org.mockito.exceptions.base.MockitoException: 
    Incorrect use of API detected here:


You probably stored a reference to `OngoingStubbing` returned by `when()` and called stubbing methods like `thenReturn()` on this reference more than once.
Examples of correct usage:
    when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);
    when(mock.isOk()).thenReturn(true, false).thenThrow(exception);

还有其他解决方案可以解决我的问题吗?不管怎样,只要问题解决了就可以了。

最佳答案

试试这个

 PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp,endTimestamp);

而不是PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp).thenReturn(endTimestamp);

关于java - 如何在同一方法中模拟第二个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41331370/

相关文章:

java - 无法让 Github 在 intellij 上显示受控版本

java - 使用 Java 8 的类流

java - 带有 React UI 的 Spring 应用程序-应用@EnableWebMvc 时如何服务?

android - 如何创建既可用于Android测试又可用于单元测试的测试类?

c++ - QSignalSpy 等待和两个信号

c# - 编写单元测试 : How to get folder with testfiles programmatically

java - 如何在 Java Junit 中测试异常

java - 如何在 android espresso 测试中向下滚动屏幕?我需要验证屏幕上的文本

java - 无法加载 ApplicationContext : IllegalArgumentException

java - 使用@SpringBootTest时如何在测试类中 Autowiring bean