使用Mockito进行RestAssured:模拟dao存储库

时间:2019-05-16 16:59:37

标签: java spring unit-testing mocking rest-assured

我正在尝试使用RestAssured并在控制器中模拟某些服务/存储库来测试我的REST端点。

这是我的测试课:

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

如您所见,我尝试在metaVersionDAO方法的顶部模拟@Test,所以我希望它像我设置的那样返回new DocVersion(),但是在此DAO中实际的代码被调用,并且在entityManager上失败,它为null。

我的问题是为什么metaVersionDAO.getMetaByVersionUUID不返回模拟对象,我应该怎么做呢?

spring-mock-mvc:3.3.0 spring-boot:2.1.2。发布

谢谢!

1 个答案:

答案 0 :(得分:0)

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

就这样:

    @MockBean
    MetaVersionDAO metaVersionDAO;

其他所有内容均与该帖子相同,并且使用了模拟实例。