How to test awt.* with SpringBoot? - java

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.

Related

unit testing spring boot with mockito

So i have searched all related questions here and found no answer that worked on mine. With that being said I am trying to unit test my spring-boot application with Mockito.
Here is my controller and the function i am trying to test.
#RestController
public class UserController {
#Autowired
UserRepository userRepository;
#GetMapping("/user")
public List<User> getAllUsers() {
return userRepository.findAll();
}
#GetMapping("/user/{id}")
public User getUser(#PathVariable Integer id) {
return userRepository.findById(id).get();
}
I am trying to test getUser function
here is my Test Controller
#RunWith(SpringJUnit4ClassRunner.class)
public class UserControllerTest {
private MockMvc mockMvc;
#MockBean
private UserController userController;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
#Test
public void getUserTest() throws Exception{
mockMvc.perform(get("/user/100").contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("application/json"))
.andExpect(jsonPath("$.role").value("deliverer"));
}
So firstly when I run this i get following error
java.lang.AssertionError: Content type not set
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:37)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:70)
at org.springframework.test.util.AssertionErrors.assertNotNull(AssertionErrors.java:106)
at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$contentTypeCompatibleWith$1(ContentResultMatchers.java:103)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at eldercare.RESTapi.controller.UserControllerTest.getUserTest(UserControllerTest.java:57)
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:567)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
with following data being printed
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
I have tested putting #ResponseBody in my Controller does not make any difference. I have also tested as stated in other post #RequestMapping(value="/user/{id}", method= RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) that doesn't work either still get the same error.
If I dont have this check .andExpect(content().contentTypeCompatibleWith("application/json")) then i get the error stating java.lang.AssertionError: No value at JSON path "$.role"
I think you should be mocking the UserRepository and not the UserController.

Assertj-swagger throws org.assertj.core.error.AssertJMultipleFailuresError Multiple Failures when executing test

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.

Can't add application.prop to Camel test

I can't make my test use application.propperies in test envirement while on main it works fine. Write that it cant find such a propperty. I tried to use #TestPropertySource(locations="classpath:application.properties") but didn't help. Also added application.propperies to resource in test folder.
My project structure
My test class:
#RunWith(SpringRunner.class)
#SpringBootTest
//#TestPropertySource(locations="classpath:application.properties")
public class Excercise5to7ApplicationTests extends CamelTestSupport {
#Override
protected RouteBuilder createRouteBuilder() {
return new MyRoute();
}
#Before
public void mockEndpoints() throws Exception {
AdviceWithRouteBuilder mockKafka = new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
// mock the for testing
interceptSendToEndpoint("kafka:*")
.skipSendToOriginalEndpoint()
.to("mock:kafka");
}
};
RouteDefinition myRoute = context.getRouteDefinition("myRoute");
myRoute.adviceWith(context, mockKafka);
}
#Test
public void testWithRealFile() throws Exception {
context.start();
MockEndpoint kafka = getMockEndpoint("mock:kafka");
kafka.expectedMessageCount(10);
kafka.assertIsSatisfied();
context.stop();
}
#Override
protected Context createJndiContext() throws Exception {
JndiContext context = new JndiContext();
context.bind("myBean", new MyBean());
return context;
}
#Override
public boolean isUseAdviceWith() {
return true;
}
}
The exception itself:
org.apache.camel.RuntimeCamelException: java.lang.IllegalArgumentException: Property with key [route.from.path] not found in properties from text: file:{{route.from.path}}?noop=true
at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1774)
at org.apache.camel.model.RouteDefinitionHelper.initRouteInputs(RouteDefinitionHelper.java:380)
at org.apache.camel.model.RouteDefinitionHelper.prepareRouteImp(RouteDefinitionHelper.java:298)
at org.apache.camel.model.RouteDefinitionHelper.prepareRoute(RouteDefinitionHelper.java:270)
at org.apache.camel.model.RoutesDefinition.route(RoutesDefinition.java:205)
at org.apache.camel.model.RoutesDefinition.from(RoutesDefinition.java:158)
at org.apache.camel.builder.RouteBuilder.from(RouteBuilder.java:169)
at com.bisnode.excercise5to7.Routes.MyRoute.configure(MyRoute.java:16)
at org.apache.camel.builder.RouteBuilder.checkInitialized(RouteBuilder.java:462)
at org.apache.camel.builder.RouteBuilder.configureRoutes(RouteBuilder.java:402)
at org.apache.camel.builder.RouteBuilder.addRoutesToCamelContext(RouteBuilder.java:383)
at org.apache.camel.impl.DefaultCamelContext$1.call(DefaultCamelContext.java:971)
at org.apache.camel.impl.DefaultCamelContext$1.call(DefaultCamelContext.java:968)
at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:3108)
at org.apache.camel.impl.DefaultCamelContext.addRoutes(DefaultCamelContext.java:968)
at org.apache.camel.test.junit4.CamelTestSupport.doSetUp(CamelTestSupport.java:352)
at org.apache.camel.test.junit4.CamelTestSupport.setUp(CamelTestSupport.java:262)
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.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.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)
Caused by: java.lang.IllegalArgumentException: Property with key [route.from.path] not found in properties from text: file:{{route.from.path}}?noop=true
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.getPropertyValue(DefaultPropertiesParser.java:271)
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.readProperty(DefaultPropertiesParser.java:157)
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.doParse(DefaultPropertiesParser.java:116)
at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.parse(DefaultPropertiesParser.java:100)
at org.apache.camel.component.properties.DefaultPropertiesParser.parseUri(DefaultPropertiesParser.java:63)
at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:230)
at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:173)
at org.apache.camel.impl.DefaultCamelContext.resolvePropertyPlaceholders(DefaultCamelContext.java:2411)
at org.apache.camel.model.ProcessorDefinitionHelper.resolvePropertyPlaceholders(ProcessorDefinitionHelper.java:735)
at org.apache.camel.model.RouteDefinitionHelper.initRouteInputs(RouteDefinitionHelper.java:378)
... 48 more
I had the same issue loading a properties file in a Test and I overrode the protected method "useOverridePropertiesWithPropertiesComponent" available through CamelTestSupport class. For example:
#Override
protected Properties useOverridePropertiesWithPropertiesComponent()
{
Properties properties = new Properties();
try
{
properties.load(new FileInputStream(
"./src/test/resources/test.properties"));
}
catch (IOException e)
{
fail(e.getMessage());
}
return properties;
}
You can find more information here: https://camel.apache.org/manual/latest/using-propertyplaceholder.html
A shorter variant of #CookieSoup answer could be to update the Camel Context for properties component.
#RunWith(CamelSpringBootRunner.class)
#ContextConfiguration
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class YourRouterTest extends CamelTestSupport
{
...
#Override
protected CamelContext createCamelContext() throws Exception
{
SimpleRegistry registry = new SimpleRegistry();
registry.put("beanName", bean);
CamelContext camelContext = new DefaultCamelContext(registry);
camelContext.addRoutes(yourRoutes);
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:application.properties");
camelContext.addComponent("properties", pc);
return camelContext;
}
...
}

Mockito not working on update/create in RESTcontroller

I'm trying to write some tests using Mockito and I managed to write them for findAll and delete operations but for the create and update, they won't work.
#RunWith(MockitoJUnitRunner.class)
public class RentedControllerTest {
#Mock
private RentedService rentalService;
#Mock
private MovieService movieService;
#Mock
private ClientService clientService;
#InjectMocks
private RentedController rentalController;
#InjectMocks
private MovieController movieController;
#InjectMocks
private ClientController clientController;
#Before
public void setUp() throws Exception {
initMocks(this);
}
#Test
public void getMovies() throws Exception {
List<Movie> movies = new ArrayList<>();
movies.add(mock(Movie.class));
// System.out.println(movies.toString());
when(movieService.findAll()).thenReturn(movies);
//// System.out.println(movieService.findAll().toString());
MoviesDto response = movieController.getMovies();
assertEquals("should be 1 movie", 1, response.getMovies().size());
}
#Test
public void updateMovie() throws Exception {
Movie movie = new Movie(2,"Lotr",0, "dir2", 2003);
MovieDto movieDto = mock(MovieDto.class);
System.out.println(movie.toString());
when(movieService.updateMovie(anyInt(), anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
// Movie m = new Movie();
// m = movieService.updateMovie(2,"Lotrrrrr",0, "dir2", 2003);
// System.out.println(m.toString());
Map<String, MovieDto> map = movieController.updateMovie(2, movieDto);
System.out.println(map.toString());
assertEquals("Title should be Lots", "Lotr", map.get("movie").getName());
}
#Test
public void createMovie() throws Exception {
Movie movie = new Movie(2,"Lotr",0, "dir2", 2003);
MovieDto movieDto = mock(MovieDto.class);
when(movieService.createMovie(anyInt(), anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
Map<String, MovieDto> map = movieController.createMovie(movieDto);
assertEquals("Title should be Lotr", "Lotr", map.get("movie").getName());
}
#Test
public void deleteMovie() throws Exception {
ResponseEntity response = movieController.deleteMovie(1);
assertEquals("Http status should be OK", HttpStatus.OK, response.getStatusCode());
}
}
So the line "when(movieService.update....) work's just fine. I tested it with the write lines as you can see in the code and it works. The problem is here
Map<String, MovieDto> map = movieController.updateMovie(2, movieDto);
I gives me NullPointerException inside that method. The method looks like this:
#RequestMapping(value = "/movies/{movieId}", method = RequestMethod.PUT, consumes = CatalogMediaType.API_JSON)
public Map<String, MovieDto> updateMovie(#PathVariable final Integer movieId,
#RequestBody final MovieDto movieDto) {
log.trace("updateMovie: movieId={} movieDto={}", movieId, movieDto);
Movie movie = movieService.updateMovie(movieId, movieDto.getMovie().getName(), movieDto.getMovie().getNumberofrentals(), movieDto.getMovie().getDirector(), movieDto.getMovie().getYear());
Map<String, MovieDto> movieDtoMap = new HashMap<>();
movieDtoMap.put("movie", new MovieDto(movie));
log.trace("updateMovie: movieDtoMap={}", movieDtoMap);
return movieDtoMap;
}
The application itself works perfectly, the problem arises only when runing the mockito tests.
java.lang.NullPointerException
at ro.ubb.stcatalog.web.controller.MovieController.updateMovie(MovieController.java:41)
at ro.ubb.stcatalog.web.controller.RentedControllerTest.updateMovie(RentedControllerTest.java:82)
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.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.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
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: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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
2016-05-26T23:51:52,845 TRACE [main]: MovieController - createMovie: moviesDto=Mock for MovieDto, hashCode: 825249556
java.lang.NullPointerException
at ro.ubb.stcatalog.web.controller.MovieController.createMovie(MovieController.java:54)
at ro.ubb.stcatalog.web.controller.RentedControllerTest.createMovie(RentedControllerTest.java:92)
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.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.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
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: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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I don't really understand what the problem is if the findAll and delete work just fine... Any ideas?
I believe the mocking of MovieDto class is causing the NPE, as your controller is expecting a few params to be present in the DTO, which are not being set by the mock(), such as movieDto.getMovie().getName().
Create a MovieDto object from scratch with all the required params, or set the params post mocking, and you should be fine.
The following should work.
#Test
public void updateMovie() throws Exception {
Movie movie = new Movie(2,"Lotr",0, "dir2", 2003);
MovieDto movieDto = mock(MovieDto.class);
// Added the following line
movieDto.setMovie(movie);
System.out.println(movie.toString());
when(movieService.updateMovie(anyInt(), anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
Map<String, MovieDto> map = movieController.updateMovie(2, movieDto);
System.out.println(map.toString());
assertEquals("Title should be Lots", "Lotr", map.get("movie").getName());
}
Looks like some dependency for the MovieController isn't getting set.
java.lang.NullPointerException
at ro.ubb.stcatalog.web.controller.MovieController.createMovie(MovieController.java:54)
You need to populate movieDto first. When you are doing get in the actual code its like you are doing get on a null which gives a NullPointer. And also Both values should be same. In when condition you are telling movieId as anyInt() and in the actual method call you are giving it as 2. That won't work. Both should be same as below.
when(movieService.updateMovie(**2**, anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
Map<String, MovieDto> map = movieController.updateMovie(**2**, movieDto);

Robolectric ShadowAssetManager nullpointer exception

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

Categories