I created a class to generate temporary files. After that I started to test the class and wrote 2 tests, see below. I excluded my generator class to be sure that none of my code causes interference.
public class TemporaryFileGeneratorTest {
private static final String SYSTEM_TEMP_DIR_PROP = "java.io.tmpdir";
private static final String DEFAULT_TEMP_DIR = System.getProperty(SYSTEM_TEMP_DIR_PROP);
#Before
public void setDefaultTempDir() {
System.setProperty(SYSTEM_TEMP_DIR_PROP, DEFAULT_TEMP_DIR);
}
#Test
public void testCreateTemporaryFile() throws IOException {
File file = File.createTempFile("temp-file", ".txt");
file.deleteOnExit();
}
#Test(expected = IOException.class)
public void testCreateTemporaryFileShouldThrowException() throws IOException {
System.setProperty(SYSTEM_TEMP_DIR_PROP, "not-existing");
File file = File.createTempFile("cannot-create-file", ".txt");
}
}
If I run the tests one-by-one, both of the tests will run successfully. But in the case of running the whole test file (by eclipse) the 'testCreateTemporaryFileShouldThrowException' will run in the first place - successfully, and 'testCreateTemporaryFile' will run secondly - with a failure.
The failure is caused by an IOException:
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createTempFile(File.java:2024)
at java.io.File.createTempFile(File.java:2070)
at mypackage.TemporaryFileGeneratorTest.testCreateTemporaryFile(TemporaryFileGeneratorTest.java:14)
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:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
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:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Anyone got an idea what is wrong? I set the system property "java.io.tmpdir" always before a test runs and this is the only change that the second test makes that needs to be reset.
Doing this way will work:
#Test
public void testCreateTemporaryFile() throws IOException {
File file = File.createTempFile("temp-file", ".txt", new File(System.getProperty(SYSTEM_TEMP_DIR_PROP)));
file.deleteOnExit();
}
#Test(expected = IOException.class)
public void testCreateTemporaryFileShouldThrowException() throws IOException {
System.setProperty(SYSTEM_TEMP_DIR_PROP, "not-existing");
File file = File.createTempFile("cannot-create-file", ".txt", new File(System.getProperty(SYSTEM_TEMP_DIR_PROP)));
}
It seems that you need to define the directory where Java will create your temp file. So, you need to set the third parameter of the method createTempFile which is the directory.
Not setting this parameter, Java gets lost, not finding the correct path. It might happen because you are changing an important system property.
Related
I have a spring boot api application and I used springfox to generate swaggerv2 api documentation and I created a test to see if my api definitions are correct.
Heres how my configuration looks like:
#Configuration
#EnableSwagger2
public class SpringFoxConfig {
#Value("${my.app.version}")
private String appVersion;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).groupName("My App").select()
.apis(RequestHandlerSelectors.basePackage("my.com.app.controller"))
.paths(regex("/api/MyAppName.*")).build()
.globalOperationParameters(
Arrays.asList(new ParameterBuilder().name("UserKey").description("Unique user key.")
.modelRef(new ModelRef("string")).parameterType("header").required(true).build()))
.apiInfo(apiInfo()).securitySchemes(Arrays.asList(apiKey()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("My App API Documentaion")
.description("This documentation is for the MyApp.").version(appVersion)
.license("MyApp.cc").licenseUrl("https://myapp.com/").build();
}
private ApiKey apiKey() {
return new ApiKey("apiKey", "APIKEY", "header");
}
}
Here's how my test looks:
#Test
public void shouldFindNoDifferences() {
File implFirstSwaggerLocation = new File(
MyTest.class.getResource("/swagger.json").getFile());
File designFirstSwaggerLocation = new File(
MyTest.class.getResource("/swagger.yaml").getFile());
SwaggerAssertions.assertThat(implFirstSwaggerLocation.getAbsolutePath())
.isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
It's exactly what they have from their examples. When I run my test It throws this exception below:
Stack trace:
org.assertj.core.error.AssertJMultipleFailuresError:
Multiple Failures (1 failure)
-- failure 1 --
[Checking Paths]
Expecting:
<["/api/myAppName",
"/api/myAppName/eventTypes",
"/api/myAppName/initialize",
"/api/myAppName/latest/{type}/{user}",
"/api/myAppName/stats/due/{ids}/custom/{days}",
"/api/myAppName/stats/due/{ids}/{period}",
"/api/myAppName/stats/orgs/most/{ids}/{period}",
"/api/myAppName/stats/orgs/{id}/{period}",
"/api/myAppName/stats/{ids}/{period}",
"/api/myAppName/stats/{ids}/{period}/{days}",
"/api/myAppName/summarize",
"/api/myAppName/{id}",
"/api/myAppName/{source}/events",
"/api/myAppName/{source}/events/batch"]>
to contain only:
<["/v2/api/myAppName/stats/orgs/{id}/{period}",
"/v2/api/myAppName/{source}/events/batch",
"/v2/api/myAppName/initialize",
"/v2/api/myAppName/eventTypes",
"/v2/api/myAppName/stats/due/{ids}/{period}",
"/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
"/v2/api/myAppName/{source}/events",
"/v2/api/myAppName/{id}",
"/v2/api/myAppName/latest/{type}/{user}",
"/v2/api/myAppName/stats/due/{ids}/custom/{days}",
"/v2/api/myAppName/stats/{ids}/{period}",
"/v2/api/myAppName",
"/v2/api/myAppName/summarize",
"/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
elements not found:
<["/v2/api/myAppName/stats/orgs/{id}/{period}",
"/v2/api/myAppName/{source}/events/batch",
"/v2/api/myAppName/initialize",
"/v2/api/myAppName/eventTypes",
"/v2/api/myAppName/stats/due/{ids}/{period}",
"/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
"/v2/api/myAppName/{source}/events",
"/v2/api/myAppName/{id}",
"/v2/api/myAppName/latest/{type}/{user}",
"/v2/api/myAppName/stats/due/{ids}/custom/{days}",
"/v2/api/myAppName/stats/{ids}/{period}",
"/v2/api/myAppName",
"/v2/api/myAppName/summarize",
"/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
and elements not expected:
<["/api/myAppName",
"/api/myAppName/eventTypes",
"/api/myAppName/initialize",
"/api/myAppName/latest/{type}/{user}",
"/api/myAppName/stats/due/{ids}/custom/{days}",
"/api/myAppName/stats/due/{ids}/{period}",
"/api/myAppName/stats/orgs/most/{ids}/{period}",
"/api/myAppName/stats/orgs/{id}/{period}",
"/api/myAppName/stats/{ids}/{period}",
"/api/myAppName/stats/{ids}/{period}/{days}",
"/api/myAppName/summarize",
"/api/myAppName/{id}",
"/api/myAppName/{source}/events",
"/api/myAppName/{source}/events/batch"]>
at DocumentationDrivenValidator.validatePaths(DocumentationDrivenValidator.java:108)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at io.github.robwin.swagger.test.DocumentationDrivenValidator.validateSwagger(DocumentationDrivenValidator.java:88)
at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:75)
at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:87)
at my.com.app.definitions.MyTest.shouldFindNoDifferences(MyTest.java:58)
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:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
I think I'm missing something.
It was my carelessness that resulted to this problem but thanks to Roddy's comment I was able to notice my mistake.
In my assertj-swagger.properties file there contains assertj.swagger.pathsPrependExpected=/v2 property that causes this issue.
I have a class which produces screenshot:
#Component
public class ImagesHandlerImpl implements ImagesHandler {
....
public boolean doScreen() throws IOException, AWTException {
final Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
...
}
}
My app created with spring boot, and I need test it. But I get java.awt.HeadlessException
My test:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = ImagesHandlerImpl.class)
#ContextConfiguration(classes = App.class)
public class ImagesHandlerImplTest {
...
#Test
public void whenDoScreenThenFilenameLikeTemplate() throws IOException, AWTException {
imagesHandler.doScreen();
final String name = dir.listFiles()[0].getName();
assertThat("SCREEN_0", is(name));
}
}
I try to prevent HeadlessException:
#SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(App.class);
builder.headless(false).run(args);
}
}
I use spring-boot version 1.5.6.RELEASE.
But it didn't help. I get log:
java.awt.HeadlessException at
sun.awt.HeadlessToolkit.getScreenSize(HeadlessToolkit.java:284) at
org.robinhood.image.ImagesHandlerImpl.doScreen(ImagesHandlerImpl.java:42)
at
org.robinhood.image.ImagesHandlerImplTest.whenDoScreenThenCreatePrintScreen(ImagesHandlerImplTest.java:51)
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:498) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at
org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at
org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at
org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at
org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at
com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at
com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Help me. How to fix this issue?
Thank You!
The spring test runner does not invoke the main method of App class.
And it will turn on Headless mode by default.
You can specify JVM argument -Djava.awt.headless=false for executing the test case.
Another solution is setting the property during bean initialization.
#Component
public class ImagesHandlerImpl implements ImagesHandler, InitializingBean {
#Override
public void afterPropertiesSet() throws Exception {
System.setProperty("java.awt.headless", "false");
}
public boolean doScreen() throws Exception {
//...
}
}
Add
// overcome #SpringBootTest setup
System.setProperty("java.awt.headless", "false")
before the doScreen() method invocation.
I got a main project, that I have to test now...
I made a second project for that, in that project, I pasted the interfaces and entities from the main project, and now I made a simple jUnit test case...
Looks like this:
public class TestLogin {
String path = "http://localhost:8080/rest/dss"; //thats the right path...
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget rtarget = client.target(path);
DssRest rest = rtarget.proxy(DssRest.class);
#Test
public void test() {
assert(rest.login(null, "Test", "Test") != -1);
}
}
DssRest, interface
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/login/{userName}/{password}")
int login(#Context HttpServletRequest req, #PathParam("userName") String userName,
#PathParam("password") String password);
from there I go to the DssBean, where the function is that I wanna test
#Override
public int login(HttpServletRequest req, String userName, String password) {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget rtarget = client.target(".../rest/mw"); //real path
MWRest rest = rtarget.proxy(MWRest.class);
int userId = rest.login(userName, password);
...
return userId; //it always is > -1
}
From there, I call the MWRest, an interface of my second project...and that project has the same function, which returns an INT, 12 for exemple...
now....to test that, made a junit test suite
#RunWith(Suite.class)
#SuiteClasses({TestLogin.class})
public class AllTests {
}
Before I run it, I made sure, the 2 projects I need to test are running...
Then I run the suite, as jUnit test, and on the JUnit console, there is this error, which I simply cannot figure out.
I hope you can help....thx
javax.ws.rs.client.ResponseProcessingException: javax.ws.rs.ProcessingException: Unable to find a MessageBodyReader of content-type application/json and type int
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.extractResult(ClientInvocation.java:140)
at org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.BodyEntityExtractor.extractEntity(BodyEntityExtractor.java:58)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:104)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:62)
at com.sun.proxy.$Proxy24.login(Unknown Source)
at test.dss.TestLogin.test(TestLogin.java:19)
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:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
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:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: javax.ws.rs.ProcessingException: Unable to find a MessageBodyReader of content-type application/json and type int
at org.jboss.resteasy.core.interception.ClientReaderInterceptorContext.throwReaderNotFound(ClientReaderInterceptorContext.java:39)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.getReader(AbstractReaderInterceptorContext.java:73)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:50)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.aroundReadFrom(GZIPDecodingInterceptor.java:59)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:53)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readFrom(ClientResponse.java:248)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readEntity(ClientResponse.java:181)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:211)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.extractResult(ClientInvocation.java:104)
... 36 more
I looked around and am a little confused if it is working or not. The result while debugging gives me the impression that it fails.
Statement 'throw new SessionTimeoutException("Session Timeout"); ' not supported
I am running a test case in Junit and have made many using exceptions previously already however they are implemented in the same manner as the method below at.
private void checkSessionTimeout(HtmlPage page) throws SessionTimeoutException {
I am new to Exceptions and do not understand why it only errors at runtime during the test.
My test runs and fails in the method inside the if statement
private void checkSessionTimeout(HtmlPage page) throws SessionTimeoutException {
HtmlDivision imgDivElement = page.getFirstByXPath("//div[#class='border']");
HtmlDivision errorDivElement = page.getFirstByXPath("//div[#class='error']");
String imgUrl = imgDivElement.getFirstElementChild().getAttribute("src");
String errorMessage = errorDivElement.getTextContent().trim();
if(page.getWebResponse().getContentAsString().contains(imgUrl) && page.getWebResponse().getContentAsString().contains(errorMessage)){
throw new SessionTimeoutException("Session Timeout");
}
}
At this line: throw new SessionTimeoutException("Session Timeout");
package com.cantShow;
import com.cantShow.htmlunit.html.HtmlPage;
import com.cantShow.TimeoutInformation;
import com.cantShow.AbstractScraperTest;
import com.cantShow.scrape.Scraper;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.cantShow.SessionTimeoutException;
public class ScraperTest extends ScraperTest<HtmlPage, SessionTimoutClassWithGettersSetters> {
#Override
protected Scraper<HtmlPage, SessionTimoutClassWithGettersSetters> getScraper() {
return new Scraper();
}
#Test
public void scrape() throws Exception {
SessionTimoutClassWithGettersSettersresult = testScraper("/scrape/timeout-session.html",
"https://cantShow.html");
details(result, "imgs/error.png","Your session has timed out. You will need to log back in to continue shopping.");
}
private static void details(SessionTimoutClassWithGettersS setterstimeoutInformation, String errorImgUrl, String errorMsg){
assertEquals(errorImgUrl, sessionTimoutClassWithGettersSetters.getErrorImageUrl());
assertEquals(errorMsg, sessionTimoutClassWithGettersSetters.getErrorMessage());
}
}
Stack Trace:
com.cantShow.Scraper.checkSessionTimeout(Scraper.java:28)
atcom.cantShow.Scraper.Scraper.scrape(Scraper.java:16)
at com.cantShow.Scraper.Scraper.scrape(Scraper.j va:12)
at com.cantShow.Scraper.ScrapeService.scrapeString(ScrapeService.java:406)
at com.cantShow.Scraper.AbstractScraperTest.testScraper(AbstractScraperTest.java:32)
at com.cantShow.Scraper.ScraperTest.scrape(ScraperTest.java:22)
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:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
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:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I have looked at other posts on Stack Overflow however could not find one like this for Java.
If you want to test that the Exception is thrown you have to catch it and verify that it is the right Exception.
#Test
public void scrape() throws Exception {
boolean exceptionHappend = false;
try {
SessionTimoutClassWithGettersSettersresult =
testScraper("/scrape/timeoutsession.html", "https://cantShow.html");
} catch (SessionTimeoutException e) {
exceptionHappend = true;
}
assertTrue(exceptionHappend);
details(result, "imgs/error.png","Your session has timed out. You will need to log back in to continue shopping.");
}
this is the error i get:
java.lang.NullPointerException
at org.robolectric.shadows.ShadowAssetManager.open(ShadowAssetManager.java:161)
at android.content.res.AssetManager.open(AssetManager.java)
at dagrada.marco.shariki.MatrixFileReader.getMatrix(MatrixFileReader.java:69)
at dagrada.marco.shariki.GameStatusHandler.loadLevel(GameStatusHandler.java:51)
at dagrada.marco.shariki.GameStatusHandler.loadGame(GameStatusHandler.java:38)
at test.GameStatusHandlerTest.testLoadGame(GameStatusHandlerTest.java:55)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:236)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
And this is the code producing it:
#RunWith(RobolectricTestRunner.class)
public class GameStatusHandlerTest {
#Mock
GraphicsRenderer renderer;
private GameStatusHandler handler;
private ArrayList<String> list = new ArrayList<>();
Context context;
#Before
public void setUp(){
context = Robolectric.application.getApplicationContext();
handler = new GameStatusHandler(context, renderer);
list.add(0, "level0.txt");
}
#Test
public void testLoadGame(){
try {
handler.loadGame(list);
} catch (Exception e) {
e.printStackTrace();
}
assertTrue(handler.getCurrentLevel() == 0);
}
Through the stactrace it's clear that the code which causes this error is a call to this method, which is a static method in the MatrixFileReader class.
public static int[][] getMatrix(Context context, String name) throws Exception {
int[][] marbles = getMatrix(context.getAssets().open(name));
return marbles;
}
}
Since the stacktrace doesn't go deeper, i guess that the problem is in the context.getAssets.open() method, but i can't figure out the reason, since the pure code is running perfectly onto both the emulator and a real device.
I am probably missing something in the test, which i am trying to run as a junit test.
As mentioned above, use RobolectricGradleTestRunner instead of RobolectricTestRunner.
Then make sure that the file you are reading is present in the assets folder of the source code: src/main/assets.
If you don't want to put it in your test folder, then you will have to specify the test asset folder as one of the asset source in your gradle build like this:
sourceSets.main {
assets.srcDirs = ['src/main/assets', 'src/test/assets']
}
Also your mock GraphicsRenderer won't be initialized with the Mock annotation as you are not using the MockitoJUnitRunner class. You have to initialize it like this in setUp().
renderer = Mockito.mock(GraphicsRenderer.class);
Please specify android manifest via #Config annotation to your test