繁体   English   中英

我嘲笑的对象是我认为的对象吗? 通缉但未调用错误

[英]Is the object I'm mocking what I think it is? Wanted but not invoked error

我有一个 setter,它设置某个 Document 对象的哈希值。 当我添加/设置属性文档(文本、发布日期、作者)时,它应该进入每个if语句并完成 stringbuilder。 我想检查update方法是否被调用,并且是用“连接的字符串”调用的。 在这种情况下,我不确定应该用update()调用什么,因此我放了一个空的""字符串。

我期待验证看起来像这样, verify(....).update(<concantenateDocStuff>.getBytes())

public void setHash() {
        StringBuilder sb = new StringBuilder();

        if (text != null) {
            sb.append(text);
        }
        if (publicationDate != null) {
            sb.append(publicationDate.toString());
        }
        if (authors != null) {
            sb.append(
                String.join(
                    "",
                    authors.stream()
                        .map(a -> a.getAuthor())
                        .collect(Collectors.toList())
                )
            );
        }
        try {
            MessageDigest msgDigest = MessageDigest.getInstance("md5");
            msgDigest.update(sb.toString().getBytes());

            hash = Hex.encodeHexString(msgDigest.digest());
        } catch (NoSuchAlgorithmException ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }
@Test
public void testSetHash() throws Exception {
        String hash = "hash";
        DateTime date = PowerMockito.mock(DateTime.class);
        Author author = Mockito.mock(Author.class);
        MessageDigest msgDigest = Mockito.mock(MessageDigest.class);
        PowerMockito.spy(MessageDigest.class);
        PowerMockito
            .doReturn(msgDigest)
            .when(MessageDigest.class)
            .getInstance("md5");
        Mockito
            .doNothing()
            .when(msgDigest)
            .update(Mockito.any(byte[].class));

        byte[] byteArray = new byte[1];
        Mockito
            .doReturn(byteArray)
            .when(msgDigest)
            .digest();

        Document testDocument = new Document();
        testDocument.setText("text");
        testDocument.setPublicationDate(date);
        testDocument.addAuthor(author);

        testDocument.setHash();

        Mockito
            .verify(msgDigest, Mockito.times(1))
            .update("".getBytes());
    }

我在嘲笑正确的对象吗?

Wanted but not invoked:
messageDigest.update([]);

重构您的方法setHash()以使其返回 String(从 set 更改为 get)。 并使hash = getHash(); 我会说在这种情况下单元测试是一个坏主意。 因为你要测试的只是你的模拟和 StringBuilder 行为。 只需进行一些集成测试:

1.Was returned String with all components(text, publicationDate, authors)
2.Was returned empty String (without all components)
3.Was thrown exception

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM