mocking—如何模拟urlconnection,以便在java中更改getlastmodified方法的返回值?

e7arh2l6  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(298)

如何模拟urlconnection以便更改getlastmodified方法的返回值?我试过几种不同的方法,比如

@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);
}

在观察家班我会

public URLConnection create(URL url) throws IOException {
        URLConnection connect = url.openConnection();
        return connect;
    }

还有一些方法来检查lastmodifieddate。但是,我的最后一个modifieddate总是返回值0。

nzrxty8p

nzrxty8p1#

像这样的事情也许。。。

// 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
        ...
    }

祝你好运!

相关问题