代码之家  ›  专栏  ›  技术社区  ›  Jeremy

mockito显示0与mock的交互

  •  1
  • Jeremy  · 技术社区  · 7 年前

    这是我的代码:

    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 回复  |  直到 7 年前
        1
  •  3
  •   bmcglynn    7 年前

    在方法调用后移动验证

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