如何模拟 URLconnection 以便我可以更改 java 中 getLastModified 方法的 return 值?
How to mock URLconnection so that I can change the return value for getLastModified method in java?
如何模拟 URLconnection 以便我可以更改 getLastModified 方法的 return 值?我尝试了几种不同的方法,例如
@Spy
Watcher watcher;
@Mock
URLConnection connection;
@Test
void status() throws IOException {
Mockito.mock(connection.getClass());
doReturn(connection).when(watcher).create(any());
doReturn((long) 3).when(connection).getLastModified();
Watcher watcher = new Watcher();
URL url = new URL("http://www.google.ats");
ConcreteObserver obs1 = new ConcreteObserver(watcher, url);
}
在观察者中 class 我会
public URLConnection create(URL url) throws IOException {
URLConnection connect = url.openConnection();
return connect;
}
还有一些检查 LastModifiedDate 的方法。但是我最后修改的日期总是 returns 值 0.
可能是这样的……
// No need for a spy
@Test
void status(
@Mock final URL urlMock,
@Mock final URLConnection urlConnectionMock
) throws Exception {
// given: The desired URL-related mocking
when(urlMock.openConnection)
.thenReturn(urlConnectionMock);
when(urlConnectionMock.getLastModified())
.thenReturn(3L);
// and:
final Watcher watcher = new Watcher();
// and:
final ConcreteObserver obs1 = new ConcreteObserver(watcher, url);
// when: The action to be tested happens
...
// then: Assert/verify the results
...
}
祝你好运!
如何模拟 URLconnection 以便我可以更改 getLastModified 方法的 return 值?我尝试了几种不同的方法,例如
@Spy
Watcher watcher;
@Mock
URLConnection connection;
@Test
void status() throws IOException {
Mockito.mock(connection.getClass());
doReturn(connection).when(watcher).create(any());
doReturn((long) 3).when(connection).getLastModified();
Watcher watcher = new Watcher();
URL url = new URL("http://www.google.ats");
ConcreteObserver obs1 = new ConcreteObserver(watcher, url);
}
在观察者中 class 我会
public URLConnection create(URL url) throws IOException {
URLConnection connect = url.openConnection();
return connect;
}
还有一些检查 LastModifiedDate 的方法。但是我最后修改的日期总是 returns 值 0.
可能是这样的……
// No need for a spy
@Test
void status(
@Mock final URL urlMock,
@Mock final URLConnection urlConnectionMock
) throws Exception {
// given: The desired URL-related mocking
when(urlMock.openConnection)
.thenReturn(urlConnectionMock);
when(urlConnectionMock.getLastModified())
.thenReturn(3L);
// and:
final Watcher watcher = new Watcher();
// and:
final ConcreteObserver obs1 = new ConcreteObserver(watcher, url);
// when: The action to be tested happens
...
// then: Assert/verify the results
...
}
祝你好运!