RestAssured with Mockito:模拟 dao 存储库

RestAssured with Mockito: mock dao repository

我正在尝试使用 RestAssured 测试我的 REST 端点,并在控制器中模拟一些 service/repositories。

这是我的测试class:

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {VedicaConfig.class})
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class RESTTest {
@LocalServerPort
    private int port;

    @Autowired
    private MockMvc mvc;

    @Mock
    MetaVersionDAO metaVersionDAO;

    @InjectMocks
    DocCtrl docCtrl;

    @Before
    public void contextLoads() {
        RestAssured.port = port;
        assertThat(mvc).isNotNull();

        // this must be called for the @Mock annotations above to be processed.
        MockitoAnnotations.initMocks(this);
        RestAssuredMockMvc.standaloneSetup(MockMvcBuilders.standaloneSetup(docCtrl));
    }

    @Test
    public void shouldGetThumbnail() {
        String ver = "1.0";
        String uuid = "124-wqer-365-asdf";
        when(metaVersionDAO.getMetaByVersionUUID(ver, uuid)).thenReturn(new DocVersion());

        given()
                .when()
                .param("uuid", uuid)
                .param("versionVed", ver)
                .get(CTX_BASE + "/thumbnail")
                .then()
                .log().ifValidationFails()
                .statusCode(OK.value())
                .contentType(ContentType.BINARY);
    }

}

现在,可以使用提供的参数正确命中 REST 端点本身。此端点已注入 DocCtrl,依次使用 metaVersionDAO 实例:

    public RawDocument getDocThumbnail(String uuid, String versionVed) throws Exception {
        DocVersion docVersion = metaVersionDAO.getMetaByVersionUUID(versionVed, uuid);
        InputStream inputStream = okmWebSrv.getOkmService().getContentByVersion(uuid, versionVed);
        String dataType = docVersion.getMetadata().getAdditionals().get(Vedantas.CONTENT_TYPE);
        ByteArrayInputStream bais = new ByteArrayInputStream(createPDFThumbnail(dataType, inputStream));

        RawDocument rawDocument = new RawDocument(bais, "qwer");
        return rawDocument;
    }

如您所见,我尝试在 @Test 方法的顶部模拟 metaVersionDAO,所以我希望它在我设置时达到 return new DocVersion()到,但是在这个 DAO 中,实际代码被调用并且它在 entityManager 上失败,它是 null。

我的问题是为什么 metaVersionDAO.getMetaByVersionUUID 没有 return 我的模拟对象,我应该怎么做才能做到这一点?

spring-mock-mvc: 3.3.0 spring-引导:2.1.2.RELEASE

谢谢!

通过将 @Mock 更改为 @MockBean 来解决。

原来如此:

    @MockBean
    MetaVersionDAO metaVersionDAO;

其他一切都与 post 中的相同,并且它使用模拟实例。