I'm trying to configure unit testing for an inherited Spring
-based project. I've tried a few things, but basically I get stuck trying to @Autowired
stuff into my test cases. Here's my setup:
A controller class that looks like this:
@Controller("serverService")
@RequestMapping("/rest/server")
@Api(value = "server")
public class ServerServiceImpl extends AbstractServiceImpl implements ServerService {
@Override
@RequestMapping(value = "/getTime", method = RequestMethod.GET)
public @ResponseBody
GatewayResponse<TimeData> getTime() {...}
ServerService
is just an interface that enables interoperation with GWT
. I'm not too worried about unit testing from GWT
right now.
AbstractServiceImpl
's main purpose is to wrap a SOAP
based web service that this server is essentially proxying and making mobile friendly. The web service is auto-generated by Apache CXF
. AbstractServiceImpl
is (roughly) as follows:
public class AbstractServiceImpl {
@Autowired
private WebServices webServices;
public WebServices getWebServices() {
return webServices;
}
In my test class I have:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:**/applicationContext.xml", "classpath:**/applicationContext-Services.xml"})
@WebAppConfiguration
public class LoginTest {
@Autowired
private ServerServiceImpl svc;
public LoginTest() {
}
@Test
public void validate() {
assertNotNull(svc);
}
}
I have no interest in trying to create mock calls to my web service with mock JSON and such. I just want to write unit tests that create un-mocked ServerServiceImpl
with un-mocked WebServices
objects and make calls to a live server.
My tests are currently failing because @Autowired
is unable to create ServerServiceImpl
. I've also tried refactoring my code to use @Autowired
for the WebServices
and use pass it to the constructor of ServerServiceImpl
, but that also fails due to @Autowired
.
Turns out this was perfectly simple. Spring will throw errors if you specify a non-existent path for an application context, for instance:
@ContextConfiguration("classpath:does-not-exist.xml")
The above will create a nice easy error message telling you what the problem is, ie a file not found exception. On the other hand this code will not:
@ContextConfiguration("classpath:**/does-not-exist.xml")
So my problem was simply that Spring couldn't find the application context XML. Ultimately I made a copy of the live context, tossed it in src/test/resources
and updated my pom.xml
's surefire-plugin
and @ContextConfiguration
as follows:
<addtionalClasspathElements>
<addtionalClasspathElement>${basedir}/src/test/resources</addtionalClasspathElement>
</addtionalClasspathElements>
@ContextConfiguration(locations = { "classpath:applicationContext.xml", "classpath:applicationContext-Services.xml" })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.