JMockit can't find EJB, get NoSuchMethodException instead - unit-testing

Trying to mock a MessageDriven bean but have trouble getting the #EJB to be injected. The #Resource works "fine" (doesn't break it at least).
If I comment out the #EJB line in MyMDB it works fine. Probably an easy thing I missed, but I can't find it...
Also I found that replacing #EJB with #Inject will make it work, but I want to know why it doesn't work with #EJB since we have a lot of code like that.
Using JDK7 and JMockit v1.39
The error I get is:
java.lang.RuntimeException: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy7.lookup()
Caused by: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy7.lookup()
at java.lang.Class.getMethod(Class.java:1678)
MyMDB.java:
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageListener;
#MessageDriven(activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "/queue/myqueue") })
public class MyMDB implements MessageListener {
#Resource(mappedName = "java:/JmsBT")
ConnectionFactory connectionFactory;
#EJB
ParConfigI parConfig;
#Override
public void onMessage(Message message) {
System.out.println("onMessage called");
}
}
MyMDBTest.java
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import org.junit.Test;
import mockit.Injectable;
import mockit.Mocked;
import mockit.Tested;
public class MyMDBTest {
#Tested
MyMDB sut;
#Injectable
ConnectionFactory jmsbt;
#Injectable
ParConfigI parConfigI;
#Mocked
Message mockedMessage;
#Test
public void testSmall() {
sut.onMessage(mockedMessage);
}
}
ParConfigI.java
import javax.ejb.Local;
#Local
public interface ParConfigI {
public void testmethod();
}

The problem is that JMockit attempts to read the lookup attribute on the #EJB annotation, but this attribute only exists in EJB 3.1+ (added in Java EE 6), not in EJB 3.0 (Java EE 5). Hence the NoSuchMethodException.
JMockit 1.40 is fixing this, but Java EE 6 has been available since early 2010. So, upgrading from the ancient Java EE 5 would also solve the problem.

Related

pojo testing with java 11

I am trying to migrate our application from java-8 to java-11. I am facing issue with pojo junit testing. This is working with java-8 , but with java-11, pojo test class is not running. It looks below dependency is not supporting for java 11.
I have below dependency in dependencies.gradle
testImplementation("pl.pojo:pojo-tester:0.7.6")
Below is my PojoTest class
package com.product.model;
import static pl.pojo.tester.api.assertion.Assertions.assertPojoMethodsFor;
import org.junit.Test;
import pl.pojo.tester.api.assertion.Method;
import com.product.CassOne;
import com.product.CassTwo;
import com.product.CassThree;
public class PojoTests {
#Test
public void testPojos() {
final Class<?>[] classesUnderTest = {
CassOne.class,
ClassTwo.class,
ClassThree.class};
for (Class<?> classUnderTest : classesUnderTest) {
assertPojoMethodsFor(classUnderTest).testing(Method.GETTER, Method.SETTER, Method.TO_STRING).areWellImplemented();
}
}
}
I am facing below Error
java.lang.NullPointerException at the line
assertPojoMethodsFor(classUnderTest).testing(Method.GETTER, Method.SETTER, Method.TO_STRING).areWellImplemented();
Any suggestion how I can resolve this or any other suggestion is most welcome.
have found alternate depedency which supports for java 11
testImplementation("com.obsidiandynamics.pojotester:pojotester:0.9.0")
You should check which version of apache-commons-lang3 you are using. Changing to versions 3.10 and up fixed the pojo issue for me.

How do I validate a json field is formatted correctly using MockMvcResultMatchers.jsonPath?

I'm trying to use a regexp to validate a value is formatted in a specific way, Lastname, Firstname (see comment where I'm making the format assertion).
The test I've written uses MockMvcResultMatchers. I can't find good documentation for this library, I can only see the API. So currently, I'm building a ResultMatcher with jsonpath assuming it will assert on the pattern matches and return me a boolean. But it only returns my the value of $.name.
Not sure what I'm doing incorrectly. I've pasted a version of the test that demonstrates what I'm trying to do.
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class SomeEntityControllerTests {
#Autowired
private MockMvc mockMvc;
private Pattern name = Pattern.compile("^[A-Za-z0-9_']+\\s?,\\s?[A-Za-z0-9_']+$");
#Test
public void getSomeEntityShouldReturnOkWithProperlyFormatted() throws Exception {
this.mockMvc.perform(get("/api/v1/someEntity/132")).andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").exists());
.andExpect(jsonPath("$.name", matches(name))); // <-- FORMAT ASSERTION NOT WORKING. Only getting the string value of $.name
}
}
Use matchesPattern of Hamcrest library http://hamcrest.org/JavaHamcrest/javadoc/2.0.0.0/org/hamcrest/text/MatchesPattern.html
String regex = "^[A-Za-z0-9_']+\\s?,\\s?[A-Za-z0-9_']+$";
#Test
public void getSomeEntityShouldReturnOkWithProperlyFormatted() throws Exception {
this.mockMvc.perform(get("/api/v1/someEntity/132")).andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").exists());
.andExpect(jsonPath("$.name", matchesPattern(regex)));
}

Tests pass with Playframework 1.2.x but fails with Playframework 1.4.x

I am migrating my application from Play1.2+Java7 to Play1.4+Java8
Play1.2+Java7 my test passes OK
Play1.4+Java8 my test fails.
I have reduced the code to the minimum and reproduced the problem. Here is the main line
The model is
package models;
import play.db.jpa.Model;
import javax.persistence.Entity;
#Entity
public class Token extends Model {
public String name;
public String role;
}
The controller is
package controllers;
import models.Token;
import play.mvc.Controller;
public class Application extends Controller {
public static void index() {
renderJSON(Token.all().fetch());
}
}
The DB test configuration is
%test.application.mode=dev
%test.db.url=jdbc:h2:mem:play;MODE=MYSQL;LOCK_MODE=0
%test.jpa.ddl=create
The test is
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.*;
import org.junit.Before;
import play.test.*;
import play.mvc.*;
import play.mvc.Http.*;
import models.*;
public class ApplicationTest extends FunctionalTest {
#Before
public void before() {
Token.deleteAll();
}
#Test
public void testThatIndexPageWorks() {
{
Response response = GET("/");
assertIsOk(response);
String content = getContent(response);
System.out.println(content);
assertFalse(content.contains("le nom"));
assertFalse(content.contains("identifier"));
}
Token t = new Token();
t.name="le nom";
t.role="identifier";
t.save();
{
Response response = GET("/");
assertIsOk(response);
String content = getContent(response);
System.out.println(content);
assertTrue(content.contains("le nom"));
assertTrue(content.contains("identifier"));
}
}
}
The behaviour is not predictable. It seems that saving entities in the tests are committed async and calling the controller depends on the threads while it did not in release 1.2
I can provide the whole project if necessary
As I do not want to use the fixtures, I have to manually sync the DB: test call of model.save() is done within a local transaction. The transaction is not closed when GET is called. the data is not flushed yet.
I thought that it was covered by
jpa FlushModeType COMMIT
It seems that it is the case in 1.2.x, but not the case in 1.4.x
I modified the test adding the code snippet below after save() and deleteAll(), and it works fine
if ( play.db.jpa.JPA.em().getTransaction().isActive()) {
play.db.jpa.JPA.em().getTransaction().commit();
play.db.jpa.JPA.em().getTransaction().begin();
}

How to write Elastic unit tests to test query building

I want to write unit tests that test the Elastic query building. I want to test that certain param values produce certain queries.
I started looking into ESTestCase. I see that you can mock a client using ESTestCase. I don't really need to mock the ES node, I just need to reproduce the query building part, but that requires the client.
Has anybody dealt with such issue?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESTestCase;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.Lists;
public class SearchRequestBuilderTests extends ESTestCase {
private static Client client;
#BeforeClass
public static void initClient() {
//this client will not be hit by any request, but it needs to be a non null proper client
//that is why we create it but we don't add any transport address to it
Settings settings = Settings.builder()
.put("", createTempDir().toString())
.build();
client = TransportClient.builder().settings(settings).build();
}
#AfterClass
public static void closeClient() {
client.close();
client = null;
}
public static Map<String, String> createSampleSearchParams() {
Map<String, String> searchParams = new HashMap<>();
searchParams.put(SenseneConstants.ADC_PARAM, "US");
searchParams.put(SenseneConstants.FETCH_SIZE_QUERY_PARAM, "10");
searchParams.put(SenseneConstants.QUERY_PARAM, "some query");
searchParams.put(SenseneConstants.LOCATION_QUERY_PARAM, "");
searchParams.put(SenseneConstants.RADIUS_QUERY_PARAM, "20");
searchParams.put(SenseneConstants.DISTANCE_UNIT_PARAM, DistanceUnit.MILES.name());
searchParams.put(SenseneConstants.GEO_DISTANCE_PARAM, "true");
return searchParams;
}
#Test
public void test() {
BasicSearcher searcher = new BasicSearcher(client); // this is my application's searcher
Map<String, String> searchParams = createSampleSearchParams();
ArrayList<String> filterQueries = Lists.newArrayList();
SearchRequest searchRequest = SearchRequest.create(searchParams, filterQueries);
MySearchRequestBuilder medleyReqBuilder = new MySearchRequestBuilder.Builder(client, "my_index", searchRequest).build();
SearchRequestBuilder searchRequestBuilder = medleyReqBuilder.constructSearchRequestBuilder();
System.out.print(searchRequestBuilder.toString());
// Here I want to assert that the search request builder output is what it should be for the above client params
}
}
I get this, and nothing in the code runs:
Assertions mismatch: -ea was not specified but -Dtests.asserts=true
REPRODUCE WITH: mvn test -Pdev -Dtests.seed=5F09BEDD71BBD14E - Dtests.class=SearchRequestBuilderTests -Dtests.locale=en_US -Dtests.timezone=America/Los_Angeles
NOTE: test params are: codec=null, sim=null, locale=null, timezone=(null)
NOTE: Mac OS X 10.10.5 x86_64/Oracle Corporation 1.7.0_80 (64-bit)/cpus=4,threads=1,free=122894936,total=128974848
NOTE: All tests run in this JVM: [SearchRequestBuilderTests]
Obviously a bit late but...
So this actually has nothing to do with the ES Testing framework but rather your run settings. Assuming you are running this in eclipse, this is actually a duplicate of Assertions mismatch: -ea was not specified but -Dtests.asserts=true.
eclipse preference -> junit -> Add -ea checkbox enable.
right click on the eclipse project -> run as -> run configure -> arguments tab -> add the -ea option in vm arguments

Java8 cannot use wsgen with a webservice endpoint that extends another class (Works with Java7)

I'm trying to use wsgen to generate wsdl files. If my webservice class extends another class I get an error but if I remove the extends it works. This is the error message:
error: compilation failed, errors should have been reported
Also wsgen -fullversion:
wsgen full version "JAX-WS RI 2.2.9-b130926.1035 svn-revision#8c29a9a53251ff741fca1664a8221dc876b2eac8"
Please note that I only have this problem when I use Java8. But the same code works when I use Java 7, and wsgen -version:
JAX-WS RI 2.2.4-b01
Here is more details and how to reproduce it:
I'm using Java8 and I have three files:
webservice
basewebservice.java
webservice.java
webserviceImpl.java
basewebservice.java:
package webservice;
public class basewebservice { }
webservice.java
package webservice;
import javax.jws.WebMethod; import javax.jws.WebService;
#WebService
public interface webservice {
#WebMethod
public String hello();
}
webserviceImpl.java
package webservice;
import javax.jws.WebService;
#WebService(endpointInterface="webservice.webservice",
serviceName="webservice")
public class webserviceImpl extends basewebservice
implements webservice {
#Override
public String hello() {
return "heLLoo";
}
}
I use this command to generate wsdl file:
wsgen -cp "." webservice.webserviceImpl -r . -wsdl
It only works when I remove the extends basewebservice.
You need to use an #XMLSeeAlso annotation on the BaseWebService. Check out this question - Java Web Services/JAXB - Abstract superclass