javax.validation.ValidationException: HV000063: Unable to instantiate class - java

I am running junit written in Custom JSR 303 Validation using ConstraintValidator. Something like this example
My Validation test class:
public class ProductV2ValidationTest {
private static Validator validator;
#Before
public void setUp() throws ExternalApiException {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
#Test
public void ValidatorTest() {
try {
ProductV2 productV2 = getObjectMapper().readValue(this.getClass().getResourceAsStream("/json/productV2Valid.json"), ProductV2.class);
Set<ConstraintViolation<ProductV2>> constraintViolations = validator.validate(productV2);
for(ConstraintViolation<ProductV2> constraintViolation : constraintViolations){
String message = constraintViolation.getMessage();
System.out.println(message);
}
assertEquals(0,constraintViolations.size());
} catch (IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
}
FYI, My validators are in some another maven project(jar),and test are written in another maven project(war).
I am getting this error:
javax.validation.ValidationException: HV000063: Unable to instantiate class com.xyz.gep.itemwrapper.external.entities.validator.NumberOfObjectsValidater.
at org.hibernate.validator.internal.util.privilegedactions.NewInstance.run(NewInstance.java:54)
at org.hibernate.validator.internal.util.ReflectionHelper.run(ReflectionHelper.java:658)
at org.hibernate.validator.internal.util.ReflectionHelper.newInstance(ReflectionHelper.java:206)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorFactoryImpl.getInstance(ConstraintValidatorFactoryImpl.java:34)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.createAndInitializeValidator(ConstraintValidatorManager.java:141)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.getInitializedValidator(ConstraintValidatorManager.java:101)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:125)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:85)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:478)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:424)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:388)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:340)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:158)
at com.rakuten.gep.itemwrapper.external.entities.validator.ProductV2ValidationTest.ValidatorTest(ProductV2ValidationTest.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.IllegalAccessException: Class org.hibernate.validator.internal.util.privilegedactions.NewInstance can not access a member of class com.rakuten.gep.itemwrapper.external.entities.validator.NumberOfObjectsValidater with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:109)
at java.lang.Class.newInstance(Class.java:368)
at org.hibernate.validator.internal.util.privilegedactions.NewInstance.run(NewInstance.java:48)
at org.hibernate.validator.internal.util.ReflectionHelper.run(ReflectionHelper.java:658)
at org.hibernate.validator.internal.util.ReflectionHelper.newInstance(ReflectionHelper.java:206)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorFactoryImpl.getInstance(ConstraintValidatorFactoryImpl.java:34)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.createAndInitializeValidator(ConstraintValidatorManager.java:141)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.getInitializedValidator(ConstraintValidatorManager.java:101)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:125)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:85)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:478)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:424)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:388)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:340)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:158)
at com.rakuten.gep.itemwrapper.external.entities.validator.ProductV2ValidationTest.ValidatorTest(ProductV2ValidationTest.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at mockit.integration.junit4.internal.BlockJUnit4ClassRunnerDecorator.executeTest(BlockJUnit4ClassRunnerDecorator.java:126)
at mockit.integration.junit4.internal.BlockJUnit4ClassRunnerDecorator.invokeExplosively(BlockJUnit4ClassRunnerDecorator.java:104)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
... 6 more
I tried adding
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
But no help .
I am using this dependancy:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.2.Final</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>

The Problem is that the hibernate validator cannot create a new instance of com.rakuten.gep.itemwrapper.external.entities.validator.NumberOfObjectsValidater because it does not have a public default constructor.
You should be able to reproduce the problem be executing the following code:
public static void test() throws InstantiationException, IllegalAccessException {
try {
com.rakuten.gep.itemwrapper.external.entities.validator.NumberOfObjectsValidater.class.newInstance();
}
catch ( InstantiationException e ) {
throw e;
}
catch ( IllegalAccessException e ) {
throw e;
}
catch ( RuntimeException e ) {
throw e;
}
}
The solution would be to add public modifier to the constructor of NumberOfObjectsValidater

add "public" to class declaration
your code:
class NumberOfObjectsValidater implements ConstraintValidator<IpAddress, String>{
}
right code:
public class NumberOfObjectsValidater implements ConstraintValidator<IpAddress, String>{
}

Related

Test static void method using power-mockito

I am trying to update our application on Java-11 from java-8, But there are many issues while running the test case after update with java-11. Most of the issues are with static class
I have tried referred the following doc as well but no luck
power Mockito reference doc
maven setup with power Mockito
Tools:
Java 11 :
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.7.7</version>
<scope>test</scope>
</dependency>
junit:junit:jar:4.13:test
import java.io.File;
public class IOUtils {
public static void deleteLocalFile(final String ... fileLocs) {
for (final String fileLoc : fileLocs) {
System.out.println("Deleting file from path: %s", fileLoc);
final File file = new File(fileLoc);
if (file.exists() && !file.isDirectory()) {
if (file.delete()) {
System.out.println("Successfully deleted the local file ");
}
else {
System.out.println("Could not delete the local file");
}
}
else {
System.out.println("Local file doesn't exist.");
}
}
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
#RunWith(PowerMockRunner.class)
#PrepareForTest(IOUtils.class)
public class IOUtilsTest {
#Test
public void testDeleteLocalFile() throws Exception {
PowerMockito.mockStatic(IOUtils.class);
String fileLocation = "/tmp/notExistingFile.txt";
PowerMockito.doNothing().when(IOUtils.class, "deleteLocalFile", anyString());
IOUtils.deleteLocalFile(fileLocation);
verifyStatic(times(1));
}
}
Exception
/Library/Java/JavaVirtualMachines/jdk-11.0.7.jdk/Contents/Home/bin/java
org.objenesis.ObjenesisException: java.lang.reflect.InvocationTargetException
at org.objenesis.instantiator.sun.SunReflectionFactoryHelper.newConstructorForSerialization(SunReflectionFactoryHelper.java:54)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.<init>(SunReflectionFactoryInstantiator.java:41)
at org.objenesis.strategy.StdInstantiatorStrategy.newInstantiatorOf(StdInstantiatorStrategy.java:68)
at org.objenesis.ObjenesisBase.getInstantiatorOf(ObjenesisBase.java:94)
at org.powermock.reflect.internal.WhiteboxImpl.newInstance(WhiteboxImpl.java:259)
at org.powermock.reflect.Whitebox.newInstance(Whitebox.java:139)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.getPowerMockTestListenersLoadedByASpecificClassLoader(AbstractTestSuiteChunkerImpl.java:95)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:174)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:48)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createTestDelegators(AbstractTestSuiteChunkerImpl.java:108)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.<init>(JUnit4TestSuiteChunkerImpl.java:71)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.<init>(AbstractCommonPowerMockRunner.java:32)
at org.powermock.modules.junit4.PowerMockRunner.<init>(PowerMockRunner.java:34)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:50)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.objenesis.instantiator.sun.SunReflectionFactoryHelper.newConstructorForSerialization(SunReflectionFactoryHelper.java:44)
... 27 more
Caused by: java.lang.IllegalAccessError: class jdk.internal.reflect.ConstructorAccessorImpl loaded by org.powermock.core.classloader.MockClassLoader #5c909414 cannot access jdk/internal/reflect superclass jdk.internal.reflect.MagicAccessorImpl
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:250)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:194)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:77)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:67)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:250)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:194)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:77)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:67)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/jdk.internal.misc.Unsafe.defineClass0(Native Method)
at java.base/jdk.internal.misc.Unsafe.defineClass(Unsafe.java:1194)
at java.base/jdk.internal.reflect.ClassDefiner.defineClass(ClassDefiner.java:63)
at java.base/jdk.internal.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:400)
at java.base/jdk.internal.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:394)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/jdk.internal.reflect.MethodAccessorGenerator.generate(MethodAccessorGenerator.java:393)
at java.base/jdk.internal.reflect.MethodAccessorGenerator.generateSerializationConstructor(MethodAccessorGenerator.java:112)
at java.base/jdk.internal.reflect.ReflectionFactory.generateConstructor(ReflectionFactory.java:514)
at java.base/jdk.internal.reflect.ReflectionFactory.newConstructorForSerialization(ReflectionFactory.java:427)
at jdk.unsupported/sun.reflect.ReflectionFactory.newConstructorForSerialization(ReflectionFactory.java:98)
... 32 more
Process finished with exit code 255

Mock static method using power mockito returning a singleton class with dao instance in its constructor

I have a singleton class which creates an instance of the dao class in its private constructor . This singleton class's instance is returned by a static method of a service class .I am trying to mock the service class using power mockito.I get am getting the error mentioned below.
Below is the Singleton class:
public class UserFilterService extends AbstractService<UserFilterDAO,UserFilter {
protected static UserFilterService instance = new UserFilterService();
private UserFilterDAO UserFilterDAO;
private UserFilterService() {
userFilterDAO = new UserFilterDAOImpl();
}
}
Below is the Service class:
public class UserServiceFactory {
public static UserFilterService getUserFilterService() {
return UserFilterService.instance;
}
}
The dependencies i have in pom.xml:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-mockito-release-full</artifactId>
<version>1.6.4</version>
<classifier>full</classifier>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.6</version>
<scope>test</scope>
</dependency>
The current test class i have
#Before
public void before() {
SuppressCode.suppressConstructor(UserFilterService.class);
PowerMockito.mockStatic(UserFilterService.class);
UserFilterService mockAlarmFilterService =
EasyMock.createMock(UserFilterService.class);
expect(UserFilterService.instance).andReturn(mockUserFilterService).anyTimes();
}
#Test
public void testgetuserFilterservice() {
UserServiceFactorymocUserFactory=Mockito.mock(UserServiceFactory.class);
when(mockEIBFactory.getuserFilterService()).thenReturn(mockUserFilterService);
}
This shows the following error:
java.lang.NoSuchMethodError:org.mockito.mock.MockCreationSettings.isUsingConstructor()Z
at org.mockito.internal.creation.instance.InstantiatorProvider.getInstantiator(InstantiatorProvider.java:10)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:59)
at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:70)
at com.avaya.eib.dam.mgmt.EIBDataServiceFactoryTest.before(EIBDataServiceFactoryTest.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

com.github.tomakehurst.wiremock.client.VerificationException: Expected status 201 for http://localhost:8080/__admin/mappings/new but was 404

This is my Test Class:
public class CompanionDevicesRestServiceTest {
public static ComDevicesRestService comDevicesRestService;
public static IComDevices cdevicesService;
public static ComDevices cdevicesRequest;
#BeforeClass
public static void init(){
cdevicesService = new StubComDevicesService();
comDevicesRestService = new ComDevicesRestService(cdevicesService);
cdevicesRequest = mock(ComDevices.class);
}
#Test
public void testPostCdevices() throws JsonProcessingException{
WireMock.stubFor(WireMock.post(WireMock.urlEqualTo("/cdevices"))
.withHeader("Accept", WireMock.equalTo("application/json"))
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("Some content")));
}
}
I am getting the following error :
com.github.tomakehurst.wiremock.client.VerificationException: Expected status 201 for http://localhost:8080/__admin/mappings/new but was 404
at com.github.tomakehurst.wiremock.client.HttpAdminClient.postJsonAssertOkAndReturnBody(HttpAdminClient.java:156)
at com.github.tomakehurst.wiremock.client.HttpAdminClient.addStubMapping(HttpAdminClient.java:65)
at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:138)
at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:134)
at com.github.tomakehurst.wiremock.client.WireMock.givenThat(WireMock.java:65)
at com.github.tomakehurst.wiremock.client.WireMock.stubFor(WireMock.java:69)
at com.charter.cdevices.rest.CompanionDevicesRestServiceTest.testPostCdevices(CompanionDevicesRestServiceTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
For this example, I suppose the wiremock was started externally,right? So you should add the configure for with the host and the port:
configureFor("localhost", 8080);
You should use the WireMock rule
#Rule
public WireMockRule wireMockRule = new WireMockRule();
and after that you could use it to create your stubs
wireMockRule.stubFor(WireMock.post(WireMock.urlEqualTo("/cdevices"))
.withHeader("Accept", WireMock.equalTo("application/json"))
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("Some content")));
ClassRule annotation can be also used:
public class CompanionDevicesRestServiceTest {
public static ComDevicesRestService comDevicesRestService;
public static IComDevices cdevicesService;
public static ComDevices cdevicesRequest;
#ClassRule
public static WireMockClassRule wireMockRule = new WireMockClassRule(wireMockConfig()
.containerThreads(20)
.port(8080)
);
#BeforeClass
public static void init(){
cdevicesService = new StubComDevicesService();
comDevicesRestService = new ComDevicesRestService(cdevicesService);
cdevicesRequest = mock(ComDevices.class);
}
#Test
public void testPostCdevices() throws JsonProcessingException{
wireMockRule.stubFor(WireMock.post(WireMock.urlEqualTo("/cdevices"))
.withHeader("Accept", WireMock.equalTo("application/json"))
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("Some content")));
}
}
and call stubFor method on the class rule object.
As per the WireMock documentation, we have three major approaches: JUnit 5.x, Junit4.x, and standalone.
My recommendation would be simple: double-check which approach is yours and proceed to the documented recommendation, but...
It never worked for me. In order to fix the issue discussed here, I did the following:
Added a #Rule to the very beginning of the test. I will share the entire class declaration down here, including the runner and a short SSL witchery to run this stuff with PowerMockRunner:
#RunWith(PowerMockRunner.class)
#PowerMockIgnore("javax.net.ssl.*")
public class StartingOddsChangesProviderIntegrationTest {
#Rule public WireMockRule wireMockRule = new WireMockRule();
(...)
You DO NOT need to do instantiate a WireMockServer, neither need you to add a server.start()/stop() line now that the #Rule annotation is there.
Finally, the WireMock depedency entry in the corresponding pom.xml file is as follows:
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>2.27.0</version>
<scope>test</scope>
</dependency>
I've tried the wiremock-jre8 artifact as well, but I ended up having the same error, so I'm pushing ahead with the wiremock-standalone.

Cannot run Robolectric tests with Gradle and Android Studio - StyleData not found

I downloaded deckard-gradle project and I have created my own with this temple.
My problem is that Robolectric.2.3 does not want to run test for class.
This is my error:
java.lang.RuntimeException: huh? can't find parent for StyleData{name='AppTheme', parent='Theme_AppCompat_Light_DarkActionBar'}
at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getParent(ShadowAssetManager.java:365)
at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getAttrValue(ShadowAssetManager.java:350)
at org.robolectric.shadows.ShadowResources.findAttributeValue(ShadowResources.java:293)
at org.robolectric.shadows.ShadowResources.attrsToTypedArray(ShadowResources.java:196)
at org.robolectric.shadows.ShadowResources.access$000(ShadowResources.java:55)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:494)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:489)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:484)
at android.content.res.Resources$Theme.obtainStyledAttributes(Resources.java)
at android.content.Context.obtainStyledAttributes(Context.java:380)
at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:104)
at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
at pl.grzeslowski.historia_miasta.activities.MainActivity_.onCreate(MainActivity_.java:31)
at android.app.Activity.performCreate(Activity.java:5133)
at org.fest.reflect.method.Invoker.invoke(Invoker.java:112)
at org.robolectric.util.ActivityController$1.run(ActivityController.java:147)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:265)
at org.robolectric.util.ActivityController.create(ActivityController.java:144)
at org.robolectric.util.ActivityController.create(ActivityController.java:154)
at pl.grzeslowski.historia_miasta.activities.MainActivityTest.testSomething(MainActivityTest.java:21)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:250)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
I run into similar problem, RobolectricTestRunner can't find the Android library dependencies. To resolve this issue you need to extend from RobolectricTestRunner to pull them in.android-maven-plugin unpacks your APK dependencies depending on version of the plugin into "target/unpack/apklibs" or to "target/unpacked-libs". The example I pasted below resolve problem for second one.
public class MyTestRunner extends RobolectricTestRunner {
public MyTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
#Override
protected AndroidManifest createAppManifest(FsFile manifestFile, FsFile resDir, FsFile assetsDir) {
return new MavenAndroidManifest( manifestFile, resDir, assetsDir);
}
public static class MavenAndroidManifest extends AndroidManifest {
public MavenAndroidManifest(FsFile androidManifestFile, FsFile resDirectory, FsFile assetsDirectory) {
super(androidManifestFile, resDirectory, assetsDirectory);
}
public MavenAndroidManifest(FsFile libraryBaseDir) {
super(libraryBaseDir);
}
#Override
protected List<FsFile> findLibraries() {
// Change "target/unpacked-libs" to "target/unpack/apklibs"
//if youe have older version of android-maven-plugin
FsFile unpack = getBaseDir().join("target/unpacked-libs");
if (unpack.exists()) {
FsFile[] libs = unpack.listFiles();
if (libs != null) {
return Arrays.asList(libs);
}
}
return Collections.emptyList();
}
#Override
protected AndroidManifest createLibraryAndroidManifest(FsFile libraryBaseDir) {
return new MavenAndroidManifest(libraryBaseDir);
}
}
}
Later in test cases use it like this:
#RunWith(MyTestRunner.class)
#Config(emulateSdk = 18)
public class MyActivityTest{
}

Error creating object MockHttpServletResponse for unit testing

I was trying to write unit test for Servlet using sprint-test using
mock object
my maven dependency is:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
I want to test just java servlet like below following book PRACTICAL TDD AND ACCEPTANCE TDD
FOR JAVA DEVELOPER :
package sample;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private boolean isValid;
/**
*
*/
private static final long serialVersionUID = 2473252741884321641L;
#Override
public void init() throws ServletException {
super.init();
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String user = req.getParameter("j_username");
String pass = req.getParameter("j_password");
if (isValidLogin(user, pass)) {
resp.sendRedirect("/frontpage");
req.getSession().setAttribute("username", user);
} else {
resp.sendRedirect("/invalidlogin");
}
}
private boolean isValidLogin(String user, String pass) {
return isValid;
}
public void setValid(boolean isValid) {
this.isValid = isValid;
}
}
My code is:
package sample;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class SprintTestProb {
#Test
public void wrongPasswordShouldRedirectToErrorPage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.addParameter("j_username", "gyanu");
request.addParameter("j_password", "wrongpassword");
LoginServlet login = new LoginServlet();
login.setValid(false);
login.doPost(request, response);
assertEquals("/invalidlogin", response.getRedirectedUrl());
}
}
I got error on line MockHttpServletResponse response = new MockHttpServletResponse();
as follows:
java.lang.ExceptionInInitializerError
at org.springframework.mock.web.MockHttpServletResponse.<init>(MockHttpServletResponse.java:76)
at sample.SprintTestProb.wrongPasswordShouldRedirectToErrorPage(SprintTestProb.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale en_US
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1499)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1322)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:721)
at javax.servlet.ServletOutputStream.<clinit>(ServletOutputStream.java:87)
... 25 more
I need to replace dependency for javaee-api with javax.selvlet-api as below:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
According to the Spring Framework Reference for Testing you should be using annotations to autowire your mocks. The example in the spring reference:
`
#WebAppConfiguration
#ContextConfiguration
public class WacTests {
#Autowired WebApplicationContext wac; // cached
#Autowired MockServletContext servletContext; // cached
#Autowired MockHttpSession session;
#Autowired MockHttpServletRequest request;
#Autowired MockHttpServletResponse response;
#Autowired ServletWebRequest webRequest;
//...
}
`
A different example (without annotations) can be found here
I had a similar issue and solved it by adding this dependency to my pom and there is no need to change your javaee-api to javax.servlet
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api-2.5</artifactId>
<version>6.1.11</version>
</dependency>

Categories