Spring boot Autowired Service and Repository throwing nullpointerexception - java

I am testing a simple beginner spring boot application, but it keeps throwing NullPointerException for my service class and my repository class.
This is my controller class:
#EnableAutoConfiguration
#RestController
public class MyController {
#Autowired
private MyService service;
#GetMapping("/welcome")
public String home throws IOException {
return service.getEntities();
}
}
This is the Service class:
#EnableAutoConfiguration
#Service
public class MyService{
#Autowired(required=true)
private MyRepository repository;
public MyService() {
};
public List<Entity> getEntities() throws IOException {
return repository.findAll();
}
And this is the repository:
#Repository
public interface MyRepository extends JpaRepository<Entity, Long>{
List<Entity> findAll();
}
So, if I run the application everything is ok. The problem is when I run this test:
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = { MyService.class, MyController.class, Entity.class })
#ComponentScan("test.firstproject")
#EntityScan(basePackages = {"test.firstproject.entities"})
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureTestDatabase(replace = Replace.NONE)
#EnableJpaRepositories("test.firstproject.repository")
#EnableAutoConfiguration
public class TestController {
private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController).build();
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
#Autowired
private ObjectMapper objectMapper;
#Test
public void allEntities() {
this.objectMapper = new ObjectMapper();
try {
ResultActions resultActions = this.mvc
.perform(MockMvcRequestBuilders.get("/welcome").accept(MediaType.APPLICATION_JSON));
this.mvc.perform(get("/welcome")).andExpect(status().isOk());
MvcResult result = resultActions.andReturn();
List<Object> list = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Entity>>(){});
for (Object c : list) {
assertTrue(c.getClass().equals(Entity.class));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
First, it threw NullPointerException when calling service.getEntities(). Then I've tried by initializing the service doing = new MyService(), but this time return repository.findAll(); throws the error. What's wrong?
EDIT - Stacktrace
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
at com.example.demo.TestController.getAllEntities(TestController.java:58)
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.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: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)
Caused by: java.lang.NullPointerException
at com.springmiddleware.controllers.MyController.allEntities(MyController.java:32)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
... 40 more

You created MyController using new in line:
private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController()).build();
Spring probably not injected Service to it. Try autowire:
#Autowired
private MyController myController;
And move MockMvc instantiation to #Before method:
private MockMvc mvc;
#Before
public void initialize() {
mvc = MockMvcBuilders.standaloneSetup(myController).build();
}

Related

How can I test IntegrationFlow with Jms.messageDrivenChannelAdapter

I tried to test IntegrationFlow which receives JMS message, then do some logic, send it to another JMS queue and then save it to the file.
I have such flow:
public class ProcessingFlow {
#Bean
public IntegrationFlow jmsProcessingFlow(
ActiveMQConnectionFactory activeMQConnectionFactory,
ValidationService validationService,
ConverterService converterService,
JmsMessageSender jmsMessageSender,
#Value("${folder.location}") String folderLocation) {
return IntegrationFlows.from(Jms.messageDrivenChannelAdapter(activeMQConnectionFactory).destination("JMSQueueFrom").id("jmsProcessing"))
.<String>handle((incomeFilePayload, messageHeaders) -> {
validationService.validate(incomeFilePayload);
String message = converterService.convert(incomeFilePayload);
jmsMessageSender.sendMessage("JMSQueueTo", message);
return incomeFilePayload;
})
.handle(Files.outboundAdapter(new File(folderLocation))
.fileNameGenerator("file.xml"))
.get();
}
}
I wrote such integration test:
#RunWith(SpringRunner.class)
#SpringIntegrationTest
#SpringBootTest(classes = {ProcessingFlowIntegrationTest.TestConfig.class})
#ActiveProfiles("test")
#DirtiesContext
public class ProcessingFlowIntegrationTest {
#MockBean
private ValidationService validationService;
#SpyBean
private ConverterService converterService;
#Autowired
private MockIntegrationContext mockIntegrationContext;
#After
public void tearDown() {
this.mockIntegrationContext.resetBeans();
}
#Test
public void shouldTestProcessingFlow() throws Exception {
TextMessage message = mock(TextMessage.class);
when(message.getText()).thenReturn(XmlContentEnum.CONTENT.getContent());
this.mockIntegrationContext.substituteMessageSourceFor("jmsProcessing", MockIntegration.mockMessageSource(message));
verify(validationService).validate(eq(message.getText()));
verify(converterService).convert(eq(message.getText()));
}
#TestConfiguration
#Import(value = {
ProcessingFlow.class,
JmsConfiguration.class,
TestConfig.class
})
static class TestConfig {
}
}
But after running I received such exception:
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'jmsProcessing' is expected to be of type 'org.springframework.integration.endpoint.SourcePollingChannelAdapter' but was actually of type 'org.springframework.integration.jms.JmsMessageDrivenEndpoint'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:399)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:215)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:157)
at org.springframework.integration.test.context.MockIntegrationContext.substituteMessageSourceFor(MockIntegrationContext.java:142)
at com.postpunk.flows.integration.ProcessingFlowIntegrationTest.shouldTestProcessingFlow(ProcessingFlowIntegrationTest.java:57)
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:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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:366)
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$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
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$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
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.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)
As I understood from exception my bean has type "org.springframework.integration.jms.JmsMessageDrivenEndpoint", but mockIntegrationContext expected "org.springframework.integration.endpoint.SourcePollingChannelAdapter". Does anybody know how can I test JmsMessageDrivenEndpoint correctly and what I did wrong?
Set noAutoStartup for the message-driven endpoint on the #SpringIntegrationTest.
Autowire the IntegrationFlow.
Then flow.getInputChannel().send(...);

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.

Assertion Error while testing rest controller Expected :200 Actual :404

I'm trying to test my simple rest controller method to get all offers but i always get java.lang.AssertionError: Status Expected :200 Actual :404. I don't know if there is problem with mocking or finding my component. I was trying to find solution in other posts but none of them was matching to my problem. Any ideas?
My Service:
#Service
#Transactional
class OfferServiceImpl implements OfferService {
private OfferRepository offerRepository;
#Autowired
public OfferServiceImpl(OfferRepository offerRepository) {
this.offerRepository = offerRepository;
}
#Override
public List<Offer> getAll(){
return (List<Offer>) offerRepository.findAll();
}
My Controller:
#RestController
#RequestMapping("/api/offers")
class OfferRestController {
private OfferService offerService;
#Autowired
public OfferRestController(OfferService offerService) {
this.offerService = offerService;
}
#GetMapping
List<Offer> getAllOffers(){
return offerService.getAll();
}
My Test Class:
#RunWith(SpringRunner.class)
#WebMvcTest(value = OfferRestController.class)
public class OfferControllerIntegrationTest {
private Offer offer1;
private Offer offer2;
#MockBean
private OfferService offerServiceMock;
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private MockMvc mvc;
#Before
public void setUpOffers(){
offer1 = new Offer("Java Dev",
4000,
5000,
"CEO",
"Java",
"Lorem ipsum",
"user#gmail.com",
true);
offer2 = new Offer("PHP Dev",
4000,
5000,
"CEO",
"PHP",
"Lorem ipsum",
"user#gmail.com",
true);
}
#Before
public void setUp() {
this.mvc = standaloneSetup(new OfferRestController(offerServiceMock))
.alwaysExpect(MockMvcResultMatchers.content()
.contentType("application/json;charset=UTF-8"))
.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON))
.alwaysExpect(status().isOk())
.build();
this.mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.alwaysDo(print())
.build();
}
#Test
public void givenOffers_whenGetOffers_thenReturnJsonArray() throws Exception{
List<Offer> allOffers= Arrays.asList(offer1,offer2);
given(offerServiceMock.getAll()).willReturn(allOffers);
mvc.perform(get("/api/offers")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$",hasSize(2)))
.andExpect(jsonPath("$[0].name").value(offer1.getName()))
.andExpect(jsonPath("$[1].name").value(offer2.getName()))
.andDo(print());
verify(offerServiceMock,times(1)).getAll();
verifyNoMoreInteractions(offerServiceMock);
}
}
My App:
#SpringBootApplication
#EntityScan(basePackageClasses = {App.class, Jsr310JpaConverters.class})
#ComponentScan({"com"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
And my problem:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/offers
Parameters = {}
Headers = {Content-Type=[application/json]}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type =
org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at brozek.com.offer.OfferControllerIntegrationTest.givenOffers_whenGetOffers_thenReturnJsonArray(OfferControllerIntegrationTest.java:89)
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:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
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.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)
Usually integration test setup should mock the controller created in the test Spring context with #WebMvcTest(value = OfferRestController.class). The usual syntax is:
#RunWith(SpringRunner.class)
#WebMvcTest(value = OfferRestController.class)
#AutoConfigureMockMvc
public class OfferRestControllerTest {
#MockBean
private OfferService offerService;
#Autowired
private MockMvc mvc;
}
In your test it's pointless to set Content-Type on GET request which has no body, remove
.contentType(MediaType.APPLICATION_JSON)
Starting from Spring 4.1 it's not necessary to use #Autowired on single constructor. You can simplify your code by removing #Autowired here:
public OfferServiceImpl(OfferRepository offerRepository) {
this.offerRepository = offerRepository;
}

SpringWS Junit Test Exception: No endpoint can be found for request [SaajSoapMessage

I am getting an exception when I try to run the Spring Web Service JUnit Test Using the Spring WebService ServerSide Integration Test using MockWebServiceClient. When I run the WebService Junit Test, I'm getting an exception:
No endpoint can be found for request [SaajSoapMessagehttp://schemas.xmlsoap.org/soap/envelope/}Envelope]
Spring_WS_ServletConfig
#Configuration
#EnableWs
#EnableTransactionManagement
// #ComponentScan({ "com.springws.endpoint", "com.mybatis.", "com.mapstruct" })
// #ImportResource({ "classpath:/SpringConfig/spring-database-config.xml" })
public class Spring_WS_ServletConfig extends WsConfigurerAdapter {
#Bean("StudentServiceWsdl")
public DefaultWsdl11Definition orders() throws SQLException {
DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
definition.setPortTypeName("StudentService_SpringWS_PortType");
definition.setLocationUri("http://localhost:8080/MvnSpringMcc/StudentService_SpringWS/");
definition.setTargetNamespace("com.springws.student/LearnSpringWs");
definition.setServiceName("SpringWSService");
// definition.setWsdl(new
// ClassPathResource("/wsdl/StudentService.wsdl"));
definition.setSchema(studentsSchema());
return definition;
}
#Bean
public XsdSchema studentsSchema() {
Resource resource = new ClassPathResource("/wsdl/StudentTask.xsd");
return new SimpleXsdSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validator = new PayloadValidatingInterceptor();
validator.setValidateRequest(true);
validator.setValidateResponse(true);
validator.setSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
}
}
TestConfig
#Configuration
#ComponentScan({ "com.springws.test", "com.mybatis.mapper.vo", "com.mybatis.service", "com.mapstruct.mapper",
"com.springws.endpoint", "com.mybatis.mapper" })
//#Import(Spring_WS_ServletConfig.class)
#ImportResource({ "classpath:testResources/spring-ws-test-database-config.xml" })
public class TestConfig {
}
CourseServiceEndPointServerSideIntegrationTest
#EnableTransactionManagement
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { TestConfig.class, Spring_WS_ServletConfig.class })
public class CourseServiceEndPointServerSideIntegrationTest {
#Autowired
ResourceLoader resourceLoader;
#Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
#Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);
}
#Test
public void courseEndpoint() throws Exception {
Resource requestPayLoad = resourceLoader.getResource("classpath:xmlTestFiles/RequestPayLoad.xml");
Resource responsePayLoad = resourceLoader.getResource("classpath:xmlTestFiles/ResponsePayLoad.xml");
mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
}
}
RequestPayLoad.xml File
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:lear="com.springws.student/LearnSpringWs" xmlns:stud="com.springws.student/StudentSchema">
<soapenv:Header />
<soapenv:Body>
<lear:GetCourseRequest>
<lear:Course>
<stud:courseID>100</stud:courseID>
</lear:Course>
</lear:GetCourseRequest>
</soapenv:Body>
</soapenv:Envelope>
Exception
CourseServiceEndpoint(com.springws.endpoint.CourseServiceEndpoint) Time elapsed: 0.219 sec <<< FAILURE!
java.lang.AssertionError: No endpoint can be found for request [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]
at org.springframework.ws.test.support.AssertionErrors.fail(AssertionErrors.java:39)
at org.springframework.ws.test.server.MockWebServiceClient.sendRequest(MockWebServiceClient.java:184)
at com.springws.serverside.test.CourseServiceEndPointServerSideIntegrationTest.courseEndpoint(CourseServiceEndPointServerSideIntegrationTest.java:41)
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: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.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.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:191)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
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.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Results :
Failed tests: CourseServiceEndpoint(com.springws.serverside.test.CourseServiceEndPointServerSideIntegrationTest): No endpoint can be found for request [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]
The better way to solve this problem is to change for proper methods in RequestCreators
and ResponseMatchers for SOAP one.
import static org.springframework.ws.test.server.RequestCreators.withSoapEnvelope;
import static org.springframework.ws.test.server.ResponseMatchers.soapEnvelope;
Changes need to be done in our test method.
Before:
mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
After:
mockClient.sendRequest(withSoapEnvelope(requestPayLoad)).andExpect(soapEnvelope(responsePayLoad));
Finally I was able to solve the problem: Just provide the Soap Payload Information in the MockWebServiceClient.sendRequest's withPayload() & andExpect(payload()) methods.
RequestPayLoad.xml
<lear:GetCourseRequest xmlns:lear="com.springws.student/LearnSpringWs"
xmlns:stud="com.springws.student/StudentSchema">
<lear:Course>
<stud:courseID>100</stud:courseID>
</lear:Course>
</lear:GetCourseRequest>
ResponsePayLoad.xml
<ns3:GetCourseResponse xmlns:ns2="com.springws.student/StudentSchema"
xmlns:ns3="com.springws.student/LearnSpringWs">
<ns3:Course>
<ns2:courseID>100</ns2:courseID>
<ns2:courseName>Physics</ns2:courseName>
<ns2:courseCategory>Physics</ns2:courseCategory>
<ns2:credit>3.0</ns2:credit>
</ns3:Course>
</ns3:GetCourseResponse>

Test spring with MockMvc

I'm trying to run a "integration test" with Spring and Junit, but i'm getting this error:
java.lang.AssertionError: Authentication should not be null
My classes:
Application.java
#SpringBootApplication
#ComponentScan
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
SecurityConfig.java
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public AuthenticationFilter authenticationFilterBean() throws Exception {
final AuthenticationFilter authenticationFilter = new AuthenticationFilter();
authenticationFilter.setAuthenticationManager(this.authenticationManagerBean());
return authenticationFilter;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers(HttpMethod.POST, "/users").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
}
LoginTests.java
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {Application.class})
#WebAppConfiguration
#TestExecutionListeners(value = DbUnitTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
#DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
#DatabaseSetup("classpath:dbunit/User.xml")
public class LoginTests {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext context;
#Resource
private AuthenticationFilter authenticationFilter;
#Test
public void login() throws Exception {
final LoginRequest loginRequest = new LoginRequest();
loginRequest.setEmail(EMAIL);
loginRequest.setPassword(PASSWORD);
mockMvc.perform(post(ENDPOINT)
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(loginRequest))
).andExpect(authenticated());
}
Error:
java.lang.AssertionError: Authentication should not be null
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:39)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:72)
at org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers$AuthenticatedMatcher.match(SecurityMockMvcResultMatchers.java:98)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at br.com.bla.studying.integration.LoginTests.login(LoginTests.java:70)
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.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:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
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:193)
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)
If i test with postman, everything works fine.
Any idea?

Categories