Mockito显示了0与模拟互动

时间:2018-12-14 21:10:37

标签: java junit mockito junit5

这是我的代码:

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.

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

1 个答案:

答案 0 :(得分:3)

在方法调用后移动验证

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