Junit code coverage in not covering the code in java using eclemma - junit

I have written the junit test case of a API helper class but when I am checking the code coverage, the helper class is showing as 0 percent. I am not sure what is the issue.
Here is the sample code:
public Class ClassHelper{
public Response invoke() {
ClassVO classVO = new ClassVO(pString);
ClassOutputVO outputVO = getSoapServiceBridgeProvider().getSoapServiceBridge(classVO).invokeProces()
...
return response
}
}
the testclass is given below:
#Test
public void testInvoke() throws Exception{
PowerMockito.whenNew(ClassVO.class).withArguments(Mockito.anyString()).thenReturn(mockVO);
Response actualResponse = (Response) classHelper.invoke();
can someone please help me with the issue? Its working with other helper classes but only happening with api helpers.
the working example has below:
#Component
public class TestHelper {
public Reponse updateRole(Request request) throws Exception {
ClassVO vo = new ClassVO();
vo.setRoleId(request.getRoleId());
vo.setRoleName(request.getRoleName());
Response response = new Response;
response.setRoleId(vo.getRoleId());
response.setRoleName(vo.getRoleName));
}
}
Test class:
#ContextConfiguration
#RunWith(PowerMockRunner.class)
#PowerMockIgnore("javax.management.*")
#PrepareForTest({ DriverManager.class })
public class TestHelperTest {
#InjectMocks
private TestHelper testHelper;
#Test
public void testUpdateRole() throws ADTMBaseException{
Request request = new Request();
request.setRoleId(8);
request.setRoleName(JUnitTestConstants.ROLE_NAME);
Reponse actualResult = testHelper.updateRole(request);
}

Related

spring boot: change print console to json rest

Actually, my project in Spring send values from the database via console, like this:
Console image, but I want to send this values via JSON like a rest API, but I don't know how to change that.
{
"depositarios": {
"correo": "correo",
"nombre": "nombre",
"numTel": "numTel",
"pApellido": "pApellido",
"SApellido": "sAellido"
}
}
this is my main class:
#SpringBootApplication
#ComponentScan("com.abner.springpostgresql.service.impl, com.abner.springpostgresql.dao.imp")
public class SpringPostgresqlApplication {
public static void main(String[] args) {
ApplicationContext context= SpringApplication.run(SpringPostgresqlApplication.class, args);
depoService depoService =context.getBean(depoService.class);
depoService.loadAllDepo();
}
}
this is my entired project source https://github.com/abnercoronado/restpostgresql
You have to create a RestController using the #RestController annotation like this:
#RestController
public class MyRestController {
#RequestMapping(value = "/personas", method = RequestMethod.GET)
public List<Persona> listaPersonas() {
// This is just a sample. Here you could bring your data form your db
List<Persona> lista = new ArrayList<Persona>();
Persona p = new Persona();
p.setNombre("angel");
p.setEdad(20);
lista.add(p);
return lista;
}
}
The value of the #RequestMapping annotation ("/personas" in this example) will be the endpoint. So when you access to the endpoint http://localhost:8080/personas (asuming that your app is running on http://localhost:8080) then you will get your data as json.
Here is an example of how to do it.
Here is another example (en espaƱol) that could help you.
You can use ObjectMapper to convert your pojo or object to JSON String and send where ever you wanted using thier API or anything.
Or you can create Rest Method and Access the API would return you the Json Value.
#RestController
public class MyRestController {
#RequestMapping(value = "/depo", method = RequestMethod.GET)
public List<?> getDepo() {
ApplicationContext context= SpringApplication.run(SpringPostgresqlApplication.class, args);
depoService depoService =context.getBean(depoService.class);
List<?> lista = depoService.loadAllDepo();
return lista;
}
Another way of doing.
#RestController
public class MyRestController {
#RequestMapping(value = "/depo", method = RequestMethod.GET)
public List<Depo> getDepo() {
ApplicationContext context= SpringApplication.run(SpringPostgresqlApplication.class, args);
depoService depoService =context.getBean(depoService.class);
List<Depo> lista = depoService.loadAllDepo();
return lista;
}
Once you start your server, you can run this by doing localhost:8080/depo. you can also return XML.

unit test spring controller with WebTestClient and ControllerAdvice

I'm trying to unit test my controller and the specific case which is : my service return a Mono.Empty, I throw a NotFoundException and I wan't to make sure I'm getting a 404 exception
here's my controller :
#GetMapping(path = "/{id}")
public Mono<MyObject<JsonNode>> getFragmentById(#PathVariable(value = "id") String id) throws NotFoundException {
return this.myService.getObject(id, JsonNode.class).switchIfEmpty(Mono.error(new NotFoundException()));
}
Here's my controller advice :
#ControllerAdvice
public class RestResponseEntityExceptionHandler {
#ExceptionHandler(value = { NotFoundException.class })
protected ResponseEntity<String> handleNotFound(SaveActionException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
}
}
and my test :
#Before
public void setup() {
client = WebTestClient.bindToController(new MyController()).controllerAdvice(new RestResponseEntityExceptionHandler()).build();
}
#Test
public void assert_404() throws Exception {
when(myService.getobject("id", JsonNode.class)).thenReturn(Mono.empty());
WebTestClient.ResponseSpec response = client.get().uri("/api/object/id").exchange();
response.expectStatus().isEqualTo(404);
}
I'm getting a NotFoundException But a 500 error not a 404 which mean my advice hasn't been called
stack trace :
java.lang.AssertionError: Status expected:<404> but was:<500>
> GET /api/fragments/idFragment
> WebTestClient-Request-Id: [1]
No content
< 500 Internal Server Error
< Content-Type: [application/json;charset=UTF-8]
Content not available yet
any idea ?
I believe you can delete this controller advice and just have the following:
#GetMapping(path = "/{id}")
public Mono<MyObject<JsonNode>> getFragmentById(#PathVariable(value = "id") String id) {
return this.myService.getObject(id, JsonNode.class)
.switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));
}
As for ResponseEntityExceptionHandler, this class is part of Spring MVC so I don't think you should use it in a WebFlux application.

Add java List in JsonObject return value

I want to add a list in the json return value. Here is my code -
#RequestMapping(value = "/servicearea", produces="application/json")
#ResponseBody
public String ServiceArea(Model model, HttpServletRequest req, HttpServletResponse res)
{
List<ServiceArea> serviceLists = locationService.getAllServiceArea();
JsonObject result = Json.createObjectBuilder()
.add("message", "test")
.add("serviceLists", serviceLists)
.build();
return result.toString();
}
'serviceLists' is the one that I want to add. I'm getting error in this line - .add("serviceLists", serviceLists). Error message is that JsonObjectBuilder is not applicable for the arguments.
Thanks in advance.
Just create a pojo like this
class ReturnPojo {
private String message;
private List<ServiceArea> serviceLists;
//getters and setters
}
And from your controller you can do
ReturnPojo returnPojo = new ReturnPojo;
returnPojo.setMessage("test");
returnPojo.setServiceLists(serviceLists);
return returnPojo;
Change the method signature to return ReturnPojo
Below solution is only useful if you are using Rest API and Spring.
create class ServiceListPojo:
public class ServiceListPOJO{
List<ServiceArea> serviceLists;
public void setServiceLists(List<ServiceArea> serviceLists){
this.serviceLists = serviceLists;
}
}
Annotate your controller with #RestController
#RestController
public class SomeController{
#RequestMapping(value = "/servicearea")
public ServiceListPOJO ServiceArea()
{
List<ServiceArea> serviceLists = locationService.getAllServiceArea();
ServiceListPOJO slp = new ServiceListPOJO();
slp.setServciceLists(serviceLists);
return slp;
}
}

How to send POST request by Spring cloud Feign

It's my Feign interface
#FeignClient(
name="mpi",
url="${mpi.url}",
configuration = FeignSimpleEncoderConfig.class
)
public interface MpiClient {
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> getPAReq(#QueryMap Map<String, String> queryMap
);
}
and my custom configuration
public class FeignSimpleEncoderConfig {
public static final int FIVE_SECONDS = 5000;
#Bean
public Logger.Level feignLogger() {
return Logger.Level.FULL;
}
#Bean
public Request.Options options() {
return new Request.Options(FIVE_SECONDS, FIVE_SECONDS);
}
#Bean
#Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder()
.encoder(new FormEncoder());
}
}
If I send request like this I see that my request send Content-Type: application/json;charset=UTF-8.
But if I set content type
consumes = "application/x-www-form-urlencoded"
I've this error message
feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type [java.util.HashMap] and content type [application/x-www-form-urlencoded]
at org.springframework.cloud.netflix.feign.support.SpringEncoder.encode(SpringEncoder.java:108) ~[spring-cloud-netflix-core-1.1.7.RELEASE.jar:1.1.7.RELEASE]
How to send POST request, I think I should make something more with Encoder.
Thanks for your help.
First of all you should change your Feign interface like this:
#FeignClient (
configuration = FeignSimpleEncoderConfig.class
)
public interface MpiClient {
#RequestMapping(method = RequestMethod.POST)
ResponseEntity<String> getPAReq(Map<String, ?> queryMap);
}
Then you should set the encoder during feign configuration:
public class FeignSimpleEncoderConfig {
#Bean
public Encoder encoder() {
return new FormEncoder();
}
}
It seems to me that Map is not valid for form body. MultiValueMap works just fine.
Feign client:
#FeignClient(name = "name", url="url", configuration = FromUrlEncodedClientConfiguration.class)
public interface PayPalFeignClient {
#RequestMapping(value = "/", method = POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
#Headers("Content-Type: application/x-www-form-urlencoded")
String foo(MultiValueMap<String, ?> formParams);
}
Config:
#Configuration
public class FromUrlEncodedClientConfiguration {
#Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
#Bean
#Primary
#Scope(SCOPE_PROTOTYPE)
Encoder feignFormEncoder() {
return new FormEncoder(new SpringEncoder(this.messageConverters));
}
}
Gradle dependencies:
compile group: 'io.github.openfeign.form', name: 'feign-form', version: '2.0.2'
compile group: 'io.github.openfeign.form', name: 'feign-form-spring', version: '2.0.5'
After that all you have to do is call it with a MultivalueMap parameter.
Specify the correct encoder for handle form encoded request
you can specify multi encoder example json/xml/formhttpurl encoded
#Bean
public Encoder feignEncoder() {
ObjectFactory<HttpMessageConverters> objectFactory = () ->
new HttpMessageConverters(new FormHttpMessageConverter());
return new SpringEncoder(objectFactory);
}
Important FormHttpMessageConverter serialize only MultiValueMap subsclass
im my case it was due to outdated version of lombok, updating to 1.18.16 resolve it

ClientResponse Failure in mockito test cases

Iam working on mockito testcases positive test methods are getting executed but comming to Exception Test methods its failing with the Exception
java.lang.Exception: Unexpected exception, expected<com.apple.ist.retail.xcard.common.exception.InvalidArgumentException> but was<org.jboss.resteasy.client.ClientResponseFailure>
at
Below is the test method which is failing and its parent class containing client object
package com.apple.ist.retail.xcard.ws.exception;
public class TestActivatePrepaidCard extends CertificateResourceTestCase {
public TestActivatePrepaidCard(String aMediaType) {
super(aMediaType);
}
#Before
public void setUp() {
super.setUp();
}
#Test(expected = InvalidArgumentException.class)
public void testActivatePrepaidCard_InvalidArgumentException()
throws DuplicateCertificateIDException, InvalidArgumentException,
DupTxnRefException, AmountException, SystemException,
XCardException {
when(
server.activatePrepaidCard(any(DiagnosticContext.class),
any(String.class), any(Number.class),
any(Amount.class), any(String.class), any(int.class),
any(HashMap.class), any(String.class),
any(SalesOrg.class), any(TxnRef.class))).thenThrow(
new InvalidArgumentException("Invalid Argument ",
INVALID_ARGUMENT));
client.activatePrepaidCard(certificateRequest);
}
Its failing near client.activatePrepaidCard(certificateRequest); with ClientResponseFailure Exception
Parent test case is
package com.apple.ist.retail.xcard.ws.exception;
#RunWith(value = Parameterized.class)
public abstract class CertificateResourceTestCase extends Assert {
protected CertificateResource client;
protected XCardServiceServer server;
protected CertificateResource resource;
protected CertificateRequest certificateRequest;
// protected Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
private String mediaType;
public CertificateResourceTestCase(String aMediaType) {
this.mediaType = aMediaType;
server = mock(XCardServiceServer.class);
CertificateResourceImpl xcardServiceRs = new CertificateResourceImpl();
xcardServiceRs.setService(server);
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(xcardServiceRs);
dispatcher.getProviderFactory().addExceptionMapper(
XCardExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
BusinessExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
RuntimeExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
BusinessExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
RuntimeExceptionMapper.class);
dispatcher.getProviderFactory()
.getServerMessageBodyWriterInterceptorRegistry()
.register(new XCardTxnWriterInterceptor());
dispatcher.getProviderFactory().getContextDataMap()
.put(HttpServletRequest.class, new MockHttpServletRequest());
client = ProxyFactory.create(CertificateResource.class, "/", new InMemoryClientExecutor(dispatcher));
diagnosticContext.setReportingRecommended(false);
}
#After
public void tearDown() throws Exception {
Mockito.reset(server);
}
Please let me know whats wrong in my code,I am pasting complete code so that I will not miss any detail
Your code is throwing an ClientResponseFailure. Debug your test and find out why. Use an exception breakpoint.