首页 > 解决方案 > Mockito 显示 0 次与 mock 的交互

问题描述

这是我的代码:

public class S3Dao {

    private final AmazonS3Client amazonS3Client;

    static final String BUCKET_NAME = "myBucket";

    public S3Dao(final AmazonS3Client amazonS3Client) {
        this.amazonS3Client = amazonS3Client;
    }

    public void put(ModelObject modelObject, String playlistId) {
        this.amazonS3Client.putObject(BUCKET_NAME, playlistId, new Gson().toJson(modelObject));
    }
}

还有我的测试代码:

@ExtendWith(MockitoExtension.class)
public class S3DaoTest {

    private S3Dao s3Dao;

    @Mock
    private AmazonS3Client s3Client;

    @BeforeEach
    public void beforeEach() {
        this.s3Dao = new S3Dao(this.s3Client);
    }

    @Test
    public void putTest() {
        ModelObject obj = new ModelObject("name", new ArrayList<>());
        String json = new Gson().toJson(obj);
        verify(s3Client).putObject(S3Dao.BUCKET_NAME, "playlistId", json);

        this.s3Dao.put(obj, "playlistId");
    }

}

产生的错误是

Wanted but not invoked:
s3Client.putObject(
    "myBucket",
    "playlistId",
    "{"name":"name","children":[]}"
);
-> at com.amazon.amazon.live.destination.playlist.dao.S3DaoTest.putTest(S3DaoTest.java:34)
Actually, there were zero interactions with this mock.

实际上,删除验证会导致测试顺利通过。为什么这不起作用?

标签: javajunitmockitojunit5

解决方案


在方法调用之后移动验证

@Test
public void putTest() {
    ModelObject obj = new ModelObject("name", new ArrayList<>());
    String json = new Gson().toJson(obj);
    this.s3Dao.put(obj, "playlistId");

    verify(s3Client).putObject(S3Dao.BUCKET_NAME, "playlistId", json);
}

推荐阅读