【问题标题】:RestAssured with Mockito: mock dao repositoryRestAssured with Mockito:模拟 dao 存储库
【发布时间】:2019-10-04 00:21:38
【问题描述】:

我正在尝试使用 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;
    }

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

我的问题是为什么metaVersionDAO.getMetaByVersionUUID 没有返回我的模拟对象,我应该怎么做才能让它返回?

spring-mock-mvc: 3.3.0 春季启动:2.1.2.RELEASE

谢谢!

【问题讨论】:

  • 尝试如下注释您的 dao:@MockBean MetaVersionDAO metaVersionDAO;,删除您的 @InjectMocks 注释,并在您的 @Before 方法中,创建您的 DocCtrl 实例并在构造函数中传递 metaVersionDAO(假设您正在使用构造函数注入)。

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


【解决方案1】:

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

原来如此:

    @MockBean
    MetaVersionDAO metaVersionDAO;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    相关资源
    最近更新 更多