PowerMockito and Mockito conflict - junit

I need to built unit tests (with junit) for a legacy system. The method that I need to test, makes use of a static method and I need to check if it's called. So, I'll need to use PowerMockito (for "regular" mocking, we use mockito).
But, when I include PowerMockito statements inside the test, Mockito fails with an org.mockito.exceptions.misusing.UnfinishedStubbingException. If I comment the lines PowerMockito.mockStatic(Application.class), PowerMockito.doNothing().when(Application.class) and PowerMockito.verifyStatic(), the UnfinishedStubbingExceptiondoes does not occur, but this way, I'm not able to check if my IllegalArgumentException occured.
The method under test looks like:
public class ClientMB {
public void loadClient(Client client) {
try {
if (client == null) {
throw new IllegalArgumentException("Client is mandatory!");
}
setClient(clientService.findById(client.getId()));
} catch (Exception ex) {
Application.handleException(ex);
}
}
}
And the test looks like:
#PrepareForTest({ Application.class })
#RunWith(PowerMockRunner.class)
public class ClientMBTest {
#Test
public final void testLoadClient() {
ClientService mockedClientService = Mockito.mock(ClientService.class);
Mockito.when(mockedClientService.findById(42L)).thenReturn(new Client());
PowerMockito.mockStatic(Application.class);
PowerMockito.doNothing().when(Application.class);
ClientMB cmb = new ClientMB(mockedClientService);
mb.loadClient(null);
PowerMockito.verifyStatic();
}
}
I imported PowerMokito using the latest version.
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
What I'm doing wrong? Any advice is welcome.

PowerMockito.doNothing().when(Application.class);
That's a stubbing command, but because you don't make a method call after the when(...), it's unfinished.
PowerMockito.doNothing().when(Application.class);
Application.someApplicationMethod();
You need to use this syntax because the normal doVerb().when(foo) syntax will provide an instance, and Java often issues a warning when trying to call a static method based on an instance instead of a class name.
If you want to stub all of Application's methods, you can do so by passing another argument into mockStatic:
PowerMockito.mockStatic(Application.class, RETURNS_SMART_NULLS);

Related

how to write junit test case for AccessTokenVerifier and JwtVerifiers in java

AccessTokenVerifier
How to write juint test case for AccessTokenverifier. I have attached the screenshot , code and dependencies details. please help if anyone know this.
please review the screershot.
Jwt token verifier source code screenshot
Source Code
log.info("JwtVerifier start building to verify the authToken");
AccessTokenVerifier jwtVerifier =
JwtVerifiers.accessTokenVerifierBuilder()
.setIssuer(oktaTokenUrlIssuer)
.setAudience(TOKEN_AUDIENCE)
.setConnectionTimeout(Duration.ofSeconds(1))
.build();
jwtVerifier.decode(authToken);
log.info("JwtVerifier build and verified the authToken successfully");
Reference Link : okta verifier
Dependencies
<dependency>
<groupId>com.okta.jwt</groupId>
<artifactId>okta-jwt-verifier</artifactId>
<version>${okta-jwt.version}</version>
</dependency>
<dependency>
<groupId>com.okta.jwt</groupId>
<artifactId>okta-jwt-verifier-impl</artifactId>
<version>${okta-jwt.version}</version>
<scope>runtime</scope>
</dependency>
I got exception when try to write test case com.okta.jwt.JwtVerificationException: Failed to parse token
Below I have attached my test case.
please refer this screenshot : My test case .
my goal is to write test case to cover 100%.
Something like this:
import org.junit.Test;
import static org.junit.Assert.*;
public class JwtVerifierTest {
#Test
public void testVerifierBuildAndVerification() {
String authToken = "valid_auth_token";
String oktaTokenUrlIssuer = "https://my-okta-instance.com";
String TOKEN_AUDIENCE = "api://default";
AccessTokenVerifier jwtVerifier =
JwtVerifiers.accessTokenVerifierBuilder()
.setIssuer(oktaTokenUrlIssuer)
.setAudience(TOKEN_AUDIENCE)
.setConnectionTimeout(Duration.ofSeconds(1))
.build();
try {
jwtVerifier.decode(authToken);
assertTrue(true);
} catch (Exception e) {
fail("Verification failed");
}
}
}

getting : java.sql.SQLException: Unknown system variable 'language' spring boot

I am beginning with spring data jpa and i have configured all spring app. in which my bootstrap class is
#SpringBootApplication
#ComponentScan("com.ticket.booking")
#EnableJpaRepositories("com.ticket.booking.dao")
#EntityScan("com.ticket.booking.entity")
public class TicketBookingManagementApplication {
public static void main(String[] args) {
SpringApplication.run(TicketBookingManagementApplication.class, args);
}
}
my controller
#RestController
#RequestMapping(value="/api/ticket")
public class TicketController {
#Autowired
private TicketService ticketService;
#GetMapping(value="/")
public String welcome(){
return "Welcome to Ticket Booking Systems";
}
#PostMapping(value="/add")
public Ticket createTicket(#RequestBody Ticket ticket){
return ticketService.createNewTicket(ticket);
}
#GetMapping(value="/get/{ticketId}")
public Ticket getTicket(#PathVariable ("ticketId") Integer ticketId){
return ticketService.getTicketById(ticketId);
}
}
service and repository
#Service
public class TicketService {
#Autowired
private TicketDao ticketDao;
public Ticket createNewTicket(Ticket ticket) {
// TODO Auto-generated method stub
return ticketDao.save(ticket);
}
public Ticket getTicketById(Integer ticketId) {
// TODO Auto-generated method stub
return ticketDao.findOne(ticketId);
}
}
public interface TicketDao extends CrudRepository<Ticket, Integer>{}
in pom.xml i have added
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
It uses mysql-connector-java-5.1.46.jar:5.1.46 and it maps req successfully but while running app i am getting error like
java.sql.SQLException: Unknown system variable 'language'
and exporting schema to database
update your mysql-connector version. it will solve your problem.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
properties:
spring.datasource.url=jdbc:mysql://localhost/schema_name
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
I am posting this answer because somebody might get benefited from this.
In my case, I was working with Spring-boot so the dependency in pom.xml was
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
So spring boot was taking some default dependency version from Spring boot parent which was different from my System installed mysql-server version 5.1.22 so that was the reason behind that error.
So to resolve this error I overridden the version by specifying manually like below.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
and it worked.

JUnit 5 vintage not running tests in nested static classes

I have JUnit 4 tests I am trying to run with JUnit 5 Vintage.
I have many tests in nested static classes. Tests in top level classes run fine, but tests in the nested classes don't run.
For example:
public class SomeOuterClass {
#Test
public void outerTest() {
// test runs
}
public static class SomeInnerTests {
#Test
public void someTest() {
// test doesn't run
}
}
public static class OtherInnerTests {
#Test
public void otherTest() {
// test doesn't run
}
}
}
I tried setting junitPlatform.filters.includeClassNamePatterns to '^.*Tests?$', '^.*Tests?\$.*$' but it didn't work.
You can execute JUnit 4 with JUnit 5 using JUnit 5 Vintage,
Use it by importing the JUnit Vintage Engine:
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit5.vintage.version}</version>
<scope>test</scope>
</dependency>
JUnit 5 Vintage added support for running nested static classes in the final release.
By default it only finds classes whose names end in "Test(s)". To include nested static classes that aren't named like that, set the following in your build file.
junitPlatform.filters.includeClassNamePatterns '^.*Tests?$', '^.*Tests?\\$.*$'

How to receive JSON Messages in POST body in a JAX-RS Restful web service in CXF?

I'm trying to develop a REST service using Apache-CXF, on top of JAX-RS. For starters, I have a method called test that receives a String message and int value. I want the clients to be able to pass these parameters in a POST message body. I can't seem to achieve this.
Before I paste the code here, here are some details:
I'm using CXF without Spring
It's not a web app, so I don't have the WEB-INF folder with the web.xml
I test the service using SoapUI and Postman (Google Chrome application)
With the following code, I get WARNING: javax.ws.rs.BadRequestException: HTTP 400 Bad Request:
DemoService.java
#WebService(targetNamespace = "http://demoservice.com")
#Path("/demoService")
public interface DemoService {
#POST
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String test (String message, int value);
}
DemoServiceImpl.java
public class DemoServiceImpl implements DemoService {
#Override
public String test(String message, int value) {
return "test message: " + message + " value = : " + value;
}
}
DemoServer.java
public class DemoServer{
public static void main(String[] args) {
JAXRSServerFactoryBean serverFactory = new JAXRSServerFactoryBean();
DemoService demoService = new DemoServiceImpl();
serverFactory.setServiceBean(demoService);
serverFactory.setAddress("http://localhost:9090");
serverFactory.create();
}
}
My POM.xml (minus the attributes in the root tag, everything's there)
<project ...>
<modelVersion>4.0.0</modelVersion>
<groupId>demo</groupId>
<artifactId>demoService</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<cxf.version>3.0.0</cxf.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
</dependency>
<!-- Jetty is needed if you're are not using the CXFServlet -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-service-description</artifactId>
<version>3.0.0-milestone1</version>
</dependency>
</dependencies>
</project>
Testing with {"message":"hello there!", "value":"50"} to the URL http://localhost:9090/demoService/test gave a HTTP 400 Bad Reuest.
Then I saw this question on S.O.: How to access parameters in a RESTful POST method and tried this:
added the following nested class in DemoServer.java:
#XmlRootElement
public static class TestRequest {
private String message;
private int value;
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public int getValue() { return value; }
public void setValue(int value) { this.value = value; }
}
I also modified the DemoService interface and the implementation to use this class as a parameter in the test method, although this is still ultimately not what I want to do. (just showing the implementation here, question's already getting long):
#Override
public String test(TestRequest testRequest) {
String message = testRequest.getMessage();
int value = testRequest.getValue();
return "test message: " + message + " value = : " + value;
}
And to fix this error that I got: SEVERE: No message body reader has been found for class DemoService$TestRequest, ContentType: application/json (in Postman I see error 415 - unsupported media type) I added the following dependencies (jettison and another thing) to the POM.xml:
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>2.6.0</version>
</dependency>
I tested the service using the following JSON message, in a HTTP POST request:
{"testRequest":{"message":"hello there!", "value":"50"}}
This works. Though this solution where I use a TestRequest class to encapsulate the parameters works, that's not the solution I'm looking for. I want to be able to pass the two parameters in a JSON message, without having to introduce this TestRequest class (explicitly).
Questions:
Would this be easier to implement using Jersey?
I don't have a web.xml nor a WEB-INF folder, so I can't configure CXF in a cxf.xml file can I? A lot of tutorials online seem ot use a lot of XML configuration, but I don't want to deploy a framework like TomEE or Spring or Glassfish just to do that.
Searching online for solutions, I came across Spring Boot. Would you recommend using that, perhaps? Would that make developing web services like this easier?
Also, how do I get it to return the value in JSON format (or is it not supposed to do that for Strings?)
My friend pointed me to this stack exchange question: JAX-RS Post multiple objects
and also the following documentation: http://cxf.apache.org/docs/jax-rs-and-jax-ws.html
which states:
public class CustomerService {
public void doIt(String a, String b) {...};
}
By default JAX-RS may not be able to handle such methods as it
requires that only a single parameter can be available in a signature
that is not annotated by one of the JAX-RS annotations like
#PathParam. So if a 'String a' parameter can be mapped to a #Path
template variable or one of the query segments then this signature
won't need to be changed :
#Path("/customers/{a}")
public class CustomerService {
public void doIt(#PathParam("a") String a, String b) {...};
}
So, to answer my question, NO, it cannot be done.

How to handle RPCs in client-server PlayN game?

I'd like to use PlayN to create a client/server card game, e.g. Hearts. While I'm mostly focusing on the HTML5 output, I'd ideally like to be output-platform-agnostic in case I decide to make an Android client in the future. How should I approach the RPC mechanism?
These are the options I've thought of:
Use JSON for RPCs with get()/post() methods - write a servlet that accepts/returns JSON, and make all versions of client code use that. This seems doable, but I'm concerned about JSON's verbosity. Once I get Hearts working I'd like to move on to more complex games, and I'm worried that JSON will result in a lot of much-larger-than-necessary messages being passed back and forth between client and server. I don't actually know how to work with JSON in Java, but I assume this is doable. Are my assumptions in-line? How well does Java work with JSON?
Continue using GWT-RPC. I can do this by taking an asynchronous service interface in my core (platform-agnostic) constructor, and in my HTML main() I pass in the GWT Async interface generated by GWT.create(MyService.class) (or at least a wrapper around it). I have no idea how well this would work for non-HTML versions though. Is it possible for me to use GWT-RPC from client-side Java code directly?
Use some other form of RPC. Any suggestions?
For the GWT RPC on the Java and Android platforms, I'm currently experimenting with using gwt-syncproxy to provide Java client access to the GWT RPC methods, and I'm using Guice, Gin, and RoboGuice on their respective target platforms to inject the appropriate asynchronous service instances for the instantiated Game object.
In the core/pom.xml for a PlayN project, I include the following dependency coordinates to support DI from Gin/Guice/RoboGuice as needed:
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
Then I add #Inject annotations to any fields inside of the concrete Game implementation:
public class TestGame implements Game {
#Inject
TestServiceAsync _testService;
...
}
In the html/pom.xml, I include the dependency coordinates for Gin:
<dependency>
<groupId>com.google.gwt.inject</groupId>
<artifactId>gin</artifactId>
<version>1.5.0</version>
</dependency>
And I create TestGameGinjector and TestGameModule classes:
TestGameGinjector.java
#GinModules(TestGameModule.class)
public interface TestGameGinjector extends Ginjector {
TestGame getGame();
}
TestGameModule.java
public class TestGameModule extends AbstractGinModule {
#Override
protected void configure() {
}
}
Since at the moment, I'm only injecting the TestServiceAsync interface, I don't need to put any implementation in the TestGameModule.configure() method; Gin manages instantiation of AsyncServices for me via GWT.create().
I then added the following to TestGame.gwt.xml
<inherits name='com.google.gwt.inject.Inject'/>
And finally, I made the following changes to TestGameHtml.java
public class TestGameHtml extends HtmlGame {
private final TestGameGinjector _injector = GWT.create(TestGameGinjector.class);
#Override
public void start() {
HtmlPlatform platform = HtmlPlatform.register();
platform.assetManager().setPathPrefix("test/");
PlayN.run(_injector.getGame());
}
}
And this pretty much covers the HTML5 platform for PlayN.
For the Java platform, I add the following dependency coordinates to java/pom.xml:
<dependency>
<groupId>com.gdevelop.gwt.syncrpc</groupId>
<artifactId>gwt-syncproxy</artifactId>
<version>0.4-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0-rc2</version>
</dependency>
Do note that the gwt-syncproxy project on Google Code does not contain a pom.xml. I have a mavenized version of gwt-syncproxy forked and available via git at https://bitbucket.org/hatboyzero/gwt-syncproxy.git. You should be able to clone it, run mvn clean package install to get it into your local Maven repository.
Anyways, I created a TestGameModule.java for the Java platform as follows:
public class TestGameModule extends AbstractModule {
#Override
protected void configure() {
bind(TestServiceAsync.class).toProvider(TestServiceProvider.class);
}
public static class TestServiceProvider implements Provider<TestServiceAsync> {
public TestServiceAsync get() {
return (TestServiceAsync) SyncProxy.newProxyInstance(
TestServiceAsync.class,
Deployment.gwtWebPath(), // URL to webapp -- http://127.0.0.1:8888/testgame
"test"
);
}
}
}
And I modified TestGameJava.java as follows:
public class TestGameJava {
public static void main(String[] args) {
Injector _injector = Guice.createInjector(new TestGameModule());
JavaPlatform platform = JavaPlatform.register();
platform.assetManager().setPathPrefix("test/images");
PlayN.run(_injector.getInstance(TestGame.class));
}
}
I went through a similar exercise with the Android platform and RoboGuice -- without going into tremendous detail, the relevant changes/snippets are as follows:
pom.xml dependencies
<dependency>
<groupId>com.gdevelop.gwt.syncrpc</groupId>
<artifactId>gwt-syncproxy</artifactId>
<version>0.4-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.roboguice</groupId>
<artifactId>roboguice</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0-rc2</version>
<classifier>no_aop</classifier>
</dependency>
TestGameApplication.java
public class TestGameApplication extends RoboApplication {
#Override
protected void addApplicationModules(List<Module> modules) {
modules.add(new TestGameModule());
}
}
TestGameModule.java
public class TestGameModule extends AbstractModule {
#Override
protected void configure() {
bind(TestServiceAsync.class).toProvider(TestServiceProvider.class);
}
public static class TestServiceProvider implements Provider<TestServiceAsync> {
public TestServiceAsync get() {
return (TestServiceAsync) SyncProxy.newProxyInstance(
TestServiceAsync.class,
Deployment.gwtWebPath(), // URL to webapp -- http://127.0.0.1:8888/testgame
"test"
);
}
}
}
TestGameActivity.java
public class TestGameActivity extends GameActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
final Injector injector = ((RoboApplication) getApplication()).getInjector();
injector.injectMembers(this);
super.onCreate(savedInstanceState);
}
#Override
public void main(){
platform().assetManager().setPathPrefix("test/images");
final Injector injector = ((RoboApplication) getApplication()).getInjector();
PlayN.run(injector.getInstance(TestGame.class));
}
}
That's a quick and dirty rundown of how I got Gin/Guice/RoboGuice + GWT working in my project, and I have verified that it works on both Java and HTML platforms beautifully.
Anyways, there's the GWT approach to providing RPC calls to multiple PlayN platforms :).