Junit Testing with SpringFramework, without Maven : Error - NoSuchMethodError - java

I'm new with JUnit - Spring Framework.
What I'm doing is, creating some Tests for my Application. Here is Code what I have did.
#RunWith(SpringJUnit4ClassRunner.class)
public class InspirdTests {
#Autowired
private PlatformBLL platform;
#Autowired
private WebApplicationContext webAppContext;
#Before
public void settingUp(){
System.out.println("Before SetUp");
}
#Test
public void setUp() throws Exception{
System.out.println("Before : " + platform);
platform.getAllProjectsForPlatform(null);
System.out.println("After : " + platform);
}
}
and the Stack Trace
java.lang.NoSuchMethodError: org.junit.runner.notification.RunNotifier.testAborted(Lorg/junit/runner/Description;Ljava/lang/Throwable;)V
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:155)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I'm just blocked, Im stucked with it, i just cant move ahead.
What I have tried:
A lot google, but the result is as it is.
I had made some blank Methods for Testing, Still Result is as it is.
I have added JUnit-4.12.jar into WEB-INF/lib/
I have added Junit 4 into Java Build Path
Guys please Help me to Find out Solution for it.

Include spring-test and junit jars in your eclipse buildpath.
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
#ContextConfiguration(locations = { "classpath:/conf/applicationContext.xml"})
#RunWith(SpringJUnit4ClassRunner.class)
public class MongoRepositoryImplTest {
#Autowired
MongoRepositoryImpl mongoRepositoryImpl;
#Test
public void testGetMongoConnectionFromFactory() {
...
}
...
Config file should look like:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<context:component-scan base-package="com.client.impl" />
<bean id="mongoRepositoryImpl" class="com.client.impl.MongoRepositoryImpl">
<constructor-arg name="connectionName" value="testCases"/>
</bean>
</beans>

Related

NullPoinerException Autowired bean - Java, Spring

I can't figure out what's wrong :/ I get NullPointerException when I run autowiredServiceTest(). I think configuration should be right, in IDE I can click through dependencies and when I pull appContext manually, then bean works, but with code bellow I get error:
Context: appCtx-watchdog-test-server.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="cz.aegis.watchdog" />
<context:annotation-config />
<bean id="helloWorldService" class="cz.aegis.watchdog.server.impl.HelloWorldServiceImpl" />
</beans>
Interface:
package cz.aegis.watchdog.api.model;
public interface HelloWorldService {
public boolean getTrue();
public String getString();
}
Impl:
package cz.aegis.watchdog.server.impl;
import cz.aegis.watchdog.api.model.HelloWorldService;
public class HelloWorldServiceImpl implements HelloWorldService {
public boolean getTrue() {
return true;
}
public String getString(){
return "helloWorld";
}
}
Testing class:
import cz.aegis.util.security.server.UserServiceHibernate;
import cz.aegis.watchdog.api.DtoTranslator;
import cz.aegis.watchdog.api.dto.MonitorTestDto;
import cz.aegis.watchdog.api.model.HelloWorldService;
import cz.aegis.watchdog.api.model.MonitorTest;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import java.sql.SQLException;
import org.testng.Assert;
import org.testng.annotations.Test;
#ContextConfiguration(locations = {"classpath:appCtx-watchdog-test-server.xml"})
public class Testing {
#Autowired
private HelloWorldService helloWorldService;
#Test
public void autowiredServiceTest() {
System.out.println(helloWorldService.getString());
Assert.assertTrue(helloWorldService.getTrue());
}
}
Error:
java.lang.NullPointerException
at Testing.autowiredServiceTest(Testing.java:37)
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.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:673)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:842)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1166)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.runWorkers(TestRunner.java:1172)
at org.testng.TestRunner.privateRun(TestRunner.java:757)
at org.testng.TestRunner.run(TestRunner.java:608)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1158)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1083)
at org.testng.TestNG.run(TestNG.java:999)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Solved, just added:
extends AbstractTestNGSpringContextTests

UISpec4J tests in Eclipse are not found

I am trying to run tests using the UISpec4J library, but Eclipse says it can not find them. I have tried restarting Eclipse, cleaning the project, etc.
The class gives no errors and I have followed the examples given on the website.
package com.health.gui;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.uispec4j.Button;
import org.uispec4j.Panel;
import org.uispec4j.UISpec4J;
import org.uispec4j.UISpecTestCase;
import org.uispec4j.Window;
import org.uispec4j.interception.WindowInterceptor;
import com.health.gui.input.xmlwizard.XmlFilePanel;
public class TestXmlFilePanel extends UISpecTestCase {
static {
UISpec4J.init();
}
private Panel panel;
#BeforeClass
public void setUp() {
panel = new Panel(new XmlFilePanel());
}
#Test
public void editWithoutSelectedTest() {
Button edit = panel.getButton("Edit selected");
Window popup = WindowInterceptor.run(edit.triggerClick());
popup.titleEquals("Warning!");
}
}
I get the following stacktrace:
junit.framework.AssertionFailedError: No tests found in com.health.gui.TestXmlFilePanel
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.TestCase.fail(TestCase.java:227)
at junit.framework.TestSuite$1.runTest(TestSuite.java:100)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I really have no clue what is wrong. Maybe you have some suggestions?
just for fun. you can remove "extends UISpecTestCase" in your class and give it a try see if it works or not :)
Junit 4.X should support annotation well and I didn't see any reason you need to extends UISpecTestCase.

HtmlUnit Class Cast Exception: TextPage cannot be cast to HtmlPage

I am trying to test my web page using spring MVC test and HTMLUnit. I need to get Html Page so that I can set value in my page and submit it but I got the following exception. How can I achieve this? Am I proceeding the right way? Please consider me as I am newbie to TDD.
Error Stack Trace:
java.lang.ClassCastException: com.gargoylesoftware.htmlunit.TextPage cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlPage
at com.demo.htmlunit.test.LoginControllerHtmlUnitTest.userLoginTest(LoginControllerHtmlUnitTest.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
And my Test Class is:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:applicationContext.xml")
#WebAppConfiguration
public class LoginControllerHtmlUnitTest {
#Autowired
private WebApplicationContext context;
private WebClient webClient;
#Before
public void setup() {
System.out.println("In set Up");
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
webClient = new WebClient();
webClient.setWebConnection(new MockMvcWebConnection(mockMvc));
}
#After
public void cleanup() {
this.webClient.closeAllWindows();
}
#Test
public void userLoginTest() {
try {
// Load the Login Form
System.out.println("In User Login Test");
HtmlPage createLoginFormPage = webClient
.getPage("http://localhost:8080/htmlunitdemo/login");
System.out.println("createLoginFormPage:"+createLoginFormPage);
// Setting Values in the Login form
HtmlForm form = createLoginFormPage.getHtmlElementById("loginForm");
HtmlTextInput usernameInput = createLoginFormPage
.getHtmlElementById("username");
usernameInput.setValueAttribute("admin");
HtmlPasswordInput passwordInput = createLoginFormPage
.getHtmlElementById("passcode");
passwordInput.setText("admin123");
HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input",
"type", "submit");
// Submitting Form
HtmlPage newPage = submit.click();
System.out.println("New Page:" + newPage.asXml());
} catch (Exception e) {
e.printStackTrace();
}
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
default-lazy-init="true">
<context:component-scan base-package="com.demo.htmlunit.controller" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
The problem is that HTML Unit is not able to cast incompleted HTML Pages (some unclosing tags, for example). So, I could solve this error using HTMLParser which is included in HTMLUnit's packages (I'm using 2.36.0v). HTMLParser completes and handles this kind of casting errors.
//Web client creation.
Page page = webClient.getPage(url);
HtmlPage tmpPage = HTMLParser.parseHtml(page.getWebResponse(), webClient.getCurrentWindow());
// use tmpPage here
HtmlSubmitInput submitBtn = currentPage.getFirstByXPath("//input[#value='Search']");
currentPage = submitBtn.click();
HtmlUnit doesn't care at all about the applicationContext.xml or your Java server code. All it matters to it is the output the server generates. If the output is random text then HtmlUnit will assume it is fetching a text file and will create a TextPage to process it. If the output is HTML then HtmlUnit will assume it is getting an HTML file and create an HtmlPage to hold the result. Based on your question you clearly need the latter.
So verify the output from your server application (http://localhost:8080/htmlunitdemo/login) and make sure it outputs valid HTML code.
replace code line:
HtmlPage newPage = submit.click();
with:
TextPage newPage = submit.click();
I do not know if I already find the solution. The error occurs when the button is Submit, not if it is a button type.
I solved it by adding a button and executing it.
HtmlElement buttonCustom = (HtmlElement) page.createElement("button");
buttonCustom.setAttribute("type", "submit");
buttonCustom.setAttribute("name", "submit");
buttonCustom.setAttribute("value", "Load");
form.appendChild(buttonCustom);

Status expected:<200> but was:<404> in spring test

I have this class:
package controllers;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashSet;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.ui.Model;
import org.springframework.web.context.WebApplicationContext;
import com.epam.hhsystem.model.candidate.Candidate;
import com.epam.hhsystem.services.CandidateService;
import com.epam.hhsystem.web.controllers.CandidateMenuController;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.context.junit4.*;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.request.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
#ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
public class CandidateControllerTest {
#Mock(name = "candidateService")
private CandidateService candidateService;
#InjectMocks
private CandidateMenuController candidateMenuController = new CandidateMenuController();
#Autowired
WebApplicationContext wac;
MockMvc mockMvc;
#Before
public void before() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}
#Test
public void testgoToCandidateMenuMockMvc() throws Exception {
//MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/goToCandidateMenu");
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/goToCandidateMenu");
ResultActions result = mockMvc.perform(request);
result.andExpect(status().isOk());
}
}
When I execute it I see:
java.lang.AssertionError: Status expected:<200> but was:<404>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:549)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at controllers.CandidateControllerTest.testgoToCandidateMenuMockMvc(CandidateControllerTest.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Controller code:
#Controller
public class CandidateMenuController extends AbstractController {
...
#RequestMapping("/goToCandidateMenu")
public String goToCandidateMenu() {
return "candidateMenu";
}
...
}
Can you help me to fix my problem?
UPDATE
BeanConfig.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Включаем опцию использования конфигурационных аннотаций (#Annotation-based configuration)-->
<context:annotation-config />
<context:component-scan base-package="com.epam.hhsystem.jpa" />
<context:component-scan base-package="com.epam.hhsystem.services" />
<!-- Файл с настройками ресурсов для работы с данными (Data Access Resources) -->
<import resource="data.xml" />
</beans>
data.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Настраивает управление транзакциями с помощью аннотации #Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Менеджер транзакций -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Непосредственно бин dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
p:url="jdbc:sqlserver://10.16.9.52:1433;databaseName=hhsystemTest;"
p:username="userNew"
p:password="Pass12345" />
<!-- Настройки фабрики сессий Хибернейта -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:test/hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create-drop</prop> -->
</props>
</property>
</bean>
</beans>
Your test setup is wrong you aren't initializing the MockMvc correctly and that is al clearly in the reference guide. FIrst of all you have twice the initializing code and you aren't assing the result of the call to the build method. So you are basically left with an empty MockMvc object.
#Before
public void before() {
MockitoAnnotations.initMocks(this);
MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}
Should be
#Before
public void before() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}
As stated this is all explained in the reference guide.
I believe you just haven't enabled <mvc:annotation-driven> in your beanconfig.xml and so your #Controller classes just aren't being registered.
Add this
<mvc:annotation-driven></mvc:annotation-driven>
In my case, I was missing the below annotation and was getting this error.
#WebMvcTest(UserStatsController.class)
public class UserStatsControllerTest {
..
}
Note that the class of the controller and NOT the test.
Make sure as well if you load other class using #ContextConfiguration(NOT the test) not load test class.
This is my working solution. Hope it helps.
#RunWith(SpringRunner.class)
#SpringBootTest(classes = Application.class)
#WebAppConfiguration
public class SimpleTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setup() throws Exception {
mockMvc = webAppContextSetup(webApplicationContext)
.build();
}
#Test
public void test() throws Exception {
mockMvc.perform(get("/simple")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().is(200));
}
}
In the case that you make a really stupid "going to fast for your own good" typo like I did, make sure that your controller test class does NOT have the same name as the controller class itself. Most people know this, but you can get into this same error condition the names are identical, and it may not my immediately obvious why. To clarify further, make sure you DO NOT DO THIS:
Controller name: MyController
Test class name: MyController
This can cause your MockMvc tests to fail with status 404... which is not very obvious.
Naming [obviously] should be more like:
Controller name: MyController
Test class name: MyControllerTest
I added this annotations to configuration class and work it:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigWebContextLoader.class)
#WebAppConfiguration
public class ResourceTest {
...
#Configuration
#EnableWebMvc
#ComponentScan( basePackages = { "..." } )
static class ContextConfiguration {
}
}
My problem was I did not have #ComponentScan() it was pretty embarrassing.
It was also hard to find.I,myself overlooked my SpringBootApplication.
Following is what i did in spring mvc which worked fine (explained as unable to find direct reference)
Controller class as folowing
package rndpurpose.controller;
#RestController
#RequestMapping("/springmvc")
public class urlController {
#CrossOrigin
#RequestMapping(value = "managepostReq", method = RequestMethod.POST, headers = "Accept=application/json")
public Map<String, Object> managepostReq()
{
Map<String, Object> response = new HashMap<>();
//System.out.println(data);
response.put("status", true);
return response;
}
}
Inside rndpurpose.text (package) > created package related to same as my #ComponentScan in WebConfig.java created test class
package rndpurpose.test;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.core.annotation.Order;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import junit.framework.Assert;
public class UrlcontrollerTest extends JunitAbstract {
#Test
#Order(1)
public void firsttestcase() throws Exception {
/*jai ganesha*/
try {
JSONObject jsonGetData = new JSONObject();
jsonGetData.put("username", "name");
ResultActions resultActions = postRequest("/springmvc/managepostReq", jsonGetData.toString());
MvcResult mvcResult = resultActions.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
JSONObject reqResponse = new JSONObject(mvcResult.getResponse().getContentAsString());
System.out.println(reqResponse);
} catch (Exception e) {
System.err.println("ERROR"+ e);
}
}
}
And JunitAbstract for handling req
package rndpurpose.test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import rndpurpose.config.WebConfig;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = WebConfig.class)
#WebAppConfiguration
#ComponentScan(basePackages="rndpurpose")
public abstract class JunitAbstract {
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
private MockMvc mockMvc;
#Autowired
public WebApplicationContext wac;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
public ResultActions postRequest(String url, String bodyData) {
ResultActions resultActions = null;
try {
System.out.println(url);
resultActions = mockMvc.perform(post(url).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content(bodyData));
}
catch (InvocationTargetException e) {
e.getCause().printStackTrace();
}
catch (Exception e) {
System.err.println("Error while executing post req "+ e);
}
return resultActions;
}
public ResultActions getRequest(String url) {
ResultActions resultActions = null;
try {
resultActions = this.mockMvc.perform(get(url)).andDo(print());
} catch (Exception e) {
System.err.println("Error while executing test case for get"+ e);
}
return resultActions;
}
public ResultActions multipartFileUpload(String url, MultiValueMap<String, String> bodyMap,
MockMultipartFile... files) {
ResultActions resultActions = null;
try {
MockMultipartHttpServletRequestBuilder builder = multipart(url);
addMultipartFiles(builder, files);
if (bodyMap != null)
builder.params(bodyMap);
resultActions = mockMvc.perform(builder);
} catch (Exception e) {
System.err.println("Error in multipartFileUpload "+ e);
}
return resultActions;
}
private void addMultipartFiles(MockMultipartHttpServletRequestBuilder builder, MockMultipartFile... files) {
if (files != null) {
for (MockMultipartFile file : files) {
builder.file(file);
}
}
}
}
and pom looks like this
<!-- test starts -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.23.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.0.0</version>
</dependency>
<!-- test ends -->
In my case, I was missing #ComponentScan("my.package.*") on MyApplication class because my controller was in a different package than MyApplication class.
Do check the debugger tick mark in debugging mode. if the component is getting scanned it will show as Tick mark else it will not.
Experienced similar error when my controllers were not loaded , in case of spring mvc with .xml based dispatcher servlet i was able to fix it by adding #ContextConfiguration
as following
Has a bean to connect db
#EnableWebMvc
public class WebConfig {
private static final Logger LOGGER = Logger.getLogger(WebConfig.class);
#Bean
public CommonsMultipartResolver multipartResolver() {
final CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(20971520);
resolver.setMaxInMemorySize(1048576);
return resolver;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:postgresql://192.168.2.29:5432/trintiygisenterprise");
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername("postgres");
dataSource.setPassword("track#123");
return dataSource;
}
#Bean
public Connection getConnectionObject() {
Connection con = null;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/t26",
"postgres", "track#123");
System.out.println("====================CONNECTED TO DB================ "+con);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
return con;
}
#Bean
#Autowired
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
and it will be scanned in springrest-servlet.xml
<context:component-scan base-package="com" />
<mvc:annotation-driven />
<!-- <mvc:resources mapping="/*" location="/" />-->
<mvc:default-servlet-handler/>
<bean class="com.config.WebConfig"/>
</beans>
and the web.xml
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Controller lookes like this
#RestController
#RequestMapping("/api")
public class bootsrapController {
/**
#GetMapping("/second")
**/
#RequestMapping(value = "second", method = RequestMethod.GET, headers =
"Accept=application/json")
public Map<String, Object> second()
{
Map<String, Object> result = new HashMap<>();
result.put("second", true);
result.put("status", true);
return result;
}
}
Testcontroller as follows
public class UrlcontrollerTest extends JunitAbstract {
#Test
#Order(1)
public void unittestcreatelayergroup(){
try {
System.out.println("Running test");
final ResultActions resultActions = getRequest("/api/second");
System.out.println(resultActions);
final MvcResult mvcResult = resultActions
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(jsonPath("status", is(true)))
.andReturn();
}
catch (final Exception e) {
LOGGER.error(e.getStackTrace());
}
}
and unit test for get req as follows
#ContextConfiguration("file:src/main/webapp/WEB-INF/springrest-servlet.xml")
#WebAppConfiguration
public abstract class JunitAbstract {
private static final Logger LOGGER = Logger.getLogger(JunitAbstract.class);
private MockMvc mockMvc;
#Autowired
public WebApplicationContext wac;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
public ResultActions getRequest(String url) {
LOGGER.info("sending req--------: "+url);
ResultActions resultActions = null;
try {
resultActions = this.mockMvc.perform(get(url)).andDo(print());
} catch (Exception e) {
LOGGER.error("Error while executing test case for get"+ e);
}
return resultActions;
}
thanks to #tunguski answer too enter link description here

Spring JUnit test keeps return nullpointerexception on my service class

UPDATE 25-11-2012
Hi it seems that my context files was in the wrong 'classpath' They had to be in the test classpath. I solved this by adding a folder called resources to the src/test/ folder. In here I could put my application contexts. I have also removed the #TestExecutionListeners from the test. I also needed to add some dependencies to my pom file for javax/servlet/serlvetException and such. If anyone is interested my code can be seen at Github, under the branch issue9.
Question [Solved]
I have made a simple application, by using spring 3. I have made a service class which uses a DAO class to map things to and from the database, by using the simple JDBC template.
My problem is when i am trying to make an integration test on these classes, it return a NullPointerException (See Stacktrace). It is really annoying since I can't seem to find the answer, so I hope you guys can help me out. Below I have posted all my different files.
Stacktrace
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.115 sec <<< FAILURE!
test(dk.martinrohwedder.blog.test.ArticleServiceTest) Time elapsed: 0.009 sec <<< ERROR!
java.lang.NullPointerException
at dk.martinrohwedder.blog.service.ArticleService.getFiveLastArticles(ArticleService.java:30)
at dk.martinrohwedder.blog.test.ArticleServiceTest.test(ArticleServiceTest.java:57)
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:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
ArticleServiceTest
package dk.martinrohwedder.blog.test;
import dk.martinrohwedder.blog.domain.Article;
import dk.martinrohwedder.blog.service.ArticleService;
import java.util.ArrayList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
*
* #author Martin Rohwedder
*/
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:test-context.xml"})
#TestExecutionListeners
#TransactionConfiguration(defaultRollback = true)
#Transactional
public class ArticleServiceTest {
#Autowired(required = true)
private ArticleService articleService;
//private EmbeddedDatabase db;
#Before
public void setUp() {
//EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
//db = builder.setType(EmbeddedDatabaseType.HSQL).setName("blog").addScript("classpath:create-db.sql").addScript("classpath:test-data.sql").build();
//articleService.getArticleDao().setDataSource(db);
//articleService = new ArticleService();
}
#After
public void tearDown() {
//articleService.getArticleDao().setDataSource(null);
//db.shutdown();
//articleService = null;
}
#Test
public void test()
{
ArrayList<Article> articles = articleService.getFiveLastArticles();
int number = articles.size();
assertEquals(3, number);
}
}
ArticleService
package dk.martinrohwedder.blog.service;
import dk.martinrohwedder.blog.domain.Article;
import dk.martinrohwedder.blog.repository.ArticleDao;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* #author Martin Rohwedder
* #since 22-11-2012
* #version 1.0
*/
#Service("articleService")
public class ArticleService {
#Autowired(required = true)
private ArticleDao articleDao;
public ArticleDao getArticleDao() {
return articleDao;
}
public void setArticleDao(ArticleDao articleDao) {
this.articleDao = articleDao;
}
public ArrayList<Article> getFiveLastArticles()
{
ArrayList<Article> articles = (ArrayList) articleDao.selectAllArticles();
if (articles.size() > 5) {
articles = (ArrayList) articles.subList(articles.size() - 6, articles.size());
}
return articles;
}
}
ArticleDao
package dk.martinrohwedder.blog.repository;
import dk.martinrohwedder.blog.domain.Article;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
/**
*
* #author Martin Rohwedder
* #since 22-11-2012
* #version 1.0
*/
#Repository
public class ArticleDao implements IArticleDao {
private JdbcTemplate jdbcTemplate;
#Autowired(required = true)
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
#Override
public List<Article> selectAllArticles() {
String sql = "select article_id, headline from article";
return this.jdbcTemplate.query(sql, new ArticleMapper());
}
#Override
public Article selectArticle(int articleId) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void insertArticle(Article article) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void updateArticle(Article article) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void deleteArticle(int articleId) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Article Mapper is responsible for map all rows found in a sql
* statement to Article objects.
*/
private static final class ArticleMapper implements RowMapper<Article> {
#Override
public Article mapRow(ResultSet rs, int rowNum) throws SQLException {
Article article = new Article();
article.setId(rs.getInt("article_id"));
article.setHeadline(rs.getString("headline"));
return article;
}
}
}
test-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
<context:component-scan base-package="dk.martinrohwedder.blog" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="embeddedDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="url" value="jdbc:hsqldb:mem:blog"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<jdbc:embedded-database id="dataSource" type="HSQL"/>
<jdbc:initialize-database data-source="embeddedDataSource">
<jdbc:script location="classpath:create-db.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:initialize-database>
</beans>
create-db.sql
create database if not exists blog;
use blog;
drop table if exists article;
create table article
(
article_id int unsigned not null auto_increment,
headline varchar(30) not null,
primary key (article_id)
);
test-data.xml
insert into article (article_headline)
values ("Artikel 1");
insert into article (article_headline)
values ("Artikel 2");
insert into article (article_headline)
values ("Artikel 3");
Both test-context.xml, create-db.sql and test-data.sql is in the classpath since they are in the package called Other Sources (src/main/resources).
Hopes that anyone can help me out.
Try using
<context:annotation-config/>
instead of
<mvc:annotation-driven />
in your test-context.xml file.
<mvc:annotation-driven/> is a tag added in Spring 3.0 which does the following:
Configures the Spring 3 Type ConversionService (alternative to
PropertyEditors)
Adds support for formatting Number fields with #NumberFormat
Adds support for formatting Date, Calendar, and Joda Time fields with #DateTimeFormat, if Joda Time is on the classpath
Adds support for validating #Controller inputs with #Valid, if a JSR-303 Provider is on the classpath
Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with #RequestBody/#ResponseBody)
Adds support for reading and writing JSON, if Jackson is o n the classpath (along the same lines as #5)
<context:annotation-config/>
Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like #Autowired, #Resource, #Required, #PostConstruct etc etc.
It looks to me like articleDao is not being set. If you want to use a Spring bean in the test then you can't instantiate the service in your test. Take this line out...
articleService = new ArticleService();

Categories

Resources