I am trying to test my REST endpoints using RestAssured
with mocking some of the service/repositories in the controller.
this is my test 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);
}
}
now, the REST endpoint itself is being hit correctly with supplied parameters. this endpoint has DocCtrl
injected which uses metaVersionDAO
instance in turn:
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;
}
as you can see, I have tried to mock metaVersionDAO
at the top of the @Test
method so I expected it to return new DocVersion()
as I set it to, but in this DAO the actual code is being called and it fails on entityManager which is null.
My question is why metaVersionDAO.getMetaByVersionUUID
doesn't return my mocked object and what should I do to make it so?
spring-mock-mvc: 3.3.0 spring-boot: 2.1.2.RELEASE
Thanks!
@MockBean MetaVersionDAO metaVersionDAO;
, removing your@InjectMocks
annotation, and in your@Before
method, create yourDocCtrl
instance and passmetaVersionDAO
in the constructor (assuming you're using constructor injection). – jolo