java,spring,web-services,spring-test
If you test an external webservice, you don't need spring. You even don't need java as you might as well write good tests with soapUI. Anyhow, if you're testing your own webservice classes, you probably have to mock some services at testing time, and therefore spring testing might help alot....
spring,spring-mvc,groovy,spring-test
You have discovered a bug in Spring's testing support. Fixed in Spring Framework 4.1.6 and 4.2 RC1 I have fixed this bug for Spring Framework 4.1.6 (scheduled for release at the end of March 2015) and 4.2 (scheduled for release in Q3 2015). For further details, please see JIRA issue...
FYI: The value attribute for @WebAppConfiguration is not an XML configuration file but rather the root directory of your web application. So your current test configuration could never work. Assuming that applicationContext.xml and webmvc-config.xml are the XML configuration files for your root and DispatcherServlet WebApplicationContexts, respectively, try redefining AbstractContextControllerTests as...
testing,annotations,junit4,spring-integration,spring-test
It depends on your application; for pure annotation configuration start with this framework test class, it has lots of tests. If you're using the Java DSL, start here....
java,spring,junit,spring-boot,spring-test
You need to annotate your test class with @ActiveProfiles as follows; otherwise, your Application configuration class will always be disabled. That's why you currently do not see any of your own beans listed in the ApplicationContext. @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @ActiveProfiles(Constants.SPRING_PROFILE_DEVELOPMENT) public class MongoDbRepositoryTest { /* ... */ } In...
spring,maven,junit,filenotfoundexception,spring-test
I was able to resolve the issue by configuring log files as below: DOMConfigurator.configure(JobLogger.class.getClassLoader().getResource("config/export/export_log.xml")) ...
java,maven,unit-testing,junit,spring-test
I have made some progress on this. As I said above, this is a multi-modular (20+) Maven application. We keep all our tests separated on one module, but Surefire's configuration were being done on the parent POM, rather on the test module's POM. After trying everything we decided to bring...
java,maven,junit,spring-test,spring-restcontroller
The proper way to achieve this is to use Spring's support for bean definition profiles. Define your DataSource beans like this: <beans ...> <!-- JNDI Based datasource --> <jee:jndi-lookup id="dataSource" jndi-name="jdbc/APMS" expected-type="javax.sql.DataSource" /> <beans profile="test"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url"...
spring-mvc,spring-boot,spring-test
The issue is that you're not returning anything. Your response body is empty. In a way it makes sense, there is no content, what would be the point in defining a Content-Type? Setting the Accept header also won't get you anywhere. Furthermore, you should be able to reproduce this same...
java,spring,testing,spring-test
Yes, this is possible via a clever hierarchical structure for your contexts. Beans in any given context can see beans in the same context as well as beans in parent contexts. You might not actually deploy your production application using such a hierarchy, but creating such a hierarchy in tests...
java,spring,unit-testing,junit,spring-test
We can do with mock. Here is sample of code. private MockMvc mockMvc; @Autowired private FilterChainProxy springSecurityFilterChain; @Autowired private WebApplicationContext wac; protected MockHttpSession session; protected MockHttpServletRequest request; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(this.springSecurityFilterChain).build(); } @Test void test(){ // I log in and then returns session HttpSession session =...
FmpdfApplication is likely annotated with @EnableAutoConfiguration (or with @SpringBootApplication which is meta-annotated with @EnableAutoConfiguration), and this will lead to Spring Security being picked up and configured via auto-configuration. If you want to see what's being auto-configured, launch your web app and access the autoconfig endpoint (e.g., http://localhost:8080/autoconfig). Then search for...
xml,spring,unit-testing,xpath,spring-test
No, it's not possible to reuse XpathResultMatchers without MockMvc and related classes. However... the code in question (in your pseudo-code example), delegates internally to Spring's XpathExpectationsHelper. So you can invoke -- for example -- the exists() method directly on an instance of XpathExpectationsHelper if you so desire. As an alternative,...
spring,validation,unit-testing,spring-test,spring-test-mvc
You cannot mock the ConstraintValidator but you certainly can mock the service that the validator depends on, using the usual spring ways of mocking beans, for eg.: .1. Potentially define a mock instance with the exact same bean name, ensuring that your config with mock gets loaded after the real...
You need to include the necessary static imports. See the Static Imports section of the Spring Reference Manual for details....
mysql,hibernate,hsqldb,spring-test
No other database has exactly the same syntax as MySQL. The next version of HSQLDB (2.3.3) has a more extensive MySQL syntax compatibility mode. This includes creation of indexes inside CREATE TABLE statements, INSERT ... ON DUPLICATE ROW UPDATE ... syntax and more. But if you still have a problem...
Sotirios was correct regarding the serverName vs. remoteHost; however, that change only gets you partially there. The following will achieve your goal: MockHttpServletRequest request = new MockHttpServletRequest(); request.setScheme("https"); request.setServerName("mycompany.com"); request.setServerPort(443); request.setRequestURI("/myapp.php"); System.out.println(request.getRequestURL()); // Prints: https://mycompany.com/myapp.php Regards, Sam...
This question is related to 10184602. Please see the discussion there for further details. But to answer your question... As per beforeTestClass() and afterTestClass() methods in org.springframework.test.context.TestContextManager, the above behaviour seems intended. Could someone explain why? As per the Javadoc, the TestContext encapsulates the context in which a test is...
spring,unit-testing,spring-test
If you have your spring configuration in an xml file you would use something like: @ContextConfiguration(locations="classpath:applicationContext.xml") If you use Java Config then you would use @ContextConfiguration(classes=Config.class) I used generic names in the above samples, you'll of course need to adapt to your project's configuration. In both cases Spring's component scanning...
I believe this is, actually, the issue you are facing. And in that same post you have an explanation from Dave Syer and a possible solution from another user. To follow Dave's advice, this would be a possible implementation of an ApplicationContextInitializer: public class MyApplicationContextInitializer implements ApplicationContextInitializer<GenericApplicationContext> { public void...
java,spring,junit,applicationcontext,spring-test
There is no need to create new ApplicationContext every time. You have to do is to use the same locations attribute in your test classes: @ContextConfiguration(locations = "classpath:test-context.xml") Spring caches application contexts by locations attribute so if the same locations appears for the second time, Spring uses the same...
spring,unit-testing,spring-test
Maarten is correct. Here is my new list of dependencies in pom/xml which worked for me: <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.5.4-Final</version> <type>pom</type> </dependency> <dependency>...
spring,junit,dependency-injection,spring-test,spring-junit
When you annotate a test class or test method with @DirtiesContext, you are telling Spring to close the ApplicationContext after that test class or method. Thus, if you later attempt to retrieve a bean from a closed context you will get an exception like you're seeing. My guess is that...
java,spring,unit-testing,junit,spring-test
Dining seems to be a class and createDining seems like a static method. No Dining object needs to be created to invoke such a method. This is equivalent to doing System.currentTimeMillis(); Spring isn't involved in static method invocations....
java,spring,testng,mockito,spring-test
You have to check out the Mockito's subproject for TestNG. You can see an example of usage here in my Mockito Cookbook repo - https://github.com/marcingrzejszczak/mockito-cookbook/blob/master/chapter01/src/test/java/com/blogspot/toomuchcoding/book/chapter1/_3_MockitoAnnotationsTestNg/assertj/MeanTaxFactorCalculatorTestNgTest.java. To use the listener you have to copy the contents of the https://github.com/mockito/mockito/tree/master/subprojects/testng/src/main/java/org/mockito/testng folder to your project since mockito-testng is not yet...
java,spring,spring-aop,spring-test,spring-aspects
Not sure what you are trying to do but your @ContextConfiguration is useless as you aren't using Spring Test to run your test (that would require a @RunWith or one of the super classes from Spring Test). Next you are adding a singleton which is already fully mocked and configured...
spring,spring-test,spring-test-mvc
Finally I resolved this issue. Since I am using standalone setup I had to define validator and messagesource. void setupTest() { MockitoAnnotations.initMocks(this) this.mockMvc = MockMvcBuilders.standaloneSetup(getController()) .setValidator(getValidator()) .alwaysDo(MockMvcResultHandlers.print()) .build() } private MessageSource getMessageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); messageSource.setUseCodeAsDefaultMessage(true); return messageSource; }...
continuous-integration,docker,continuous-deployment,spring-test,integration-tests
The Spring MVC Test Framework (i.e., MockMvc) can not be used to test a Spring web application deployed in a Servlet container. On the contrary, the primary goal of the Spring MVC Test Framework is to provide first-class "support for testing client and server-side Spring MVC code through a fluent...
java,junit,spring-boot,spring-test
Your code is OK. The fault is in schema-hsqldb.sql. Just add the following two lines at the beginning of the file: DROP TABLE CLICK IF EXISTS; DROP TABLE SHORTURL IF EXISTS; That ensures that each time the database is recreated, existing tables are dropped....
As Marten mentioned, @IntegrationTest should only be used when you need to test against the deployed Spring Boot application (e.g., deployed in an embedded Tomcat, Jetty, or Undertow container). So if your goal is to test your repository layer in isolation, you should not use @IntegrationTest. On the other hand,...
java,spring,hibernate,junit,spring-test
If I understand correctly, your project entities are in fact Spring beans coming from the Spring context. The Spring context, by default, is shared between tests. The first test attaches these entities to the session using saveOrUpdate() and thus generates an ID for them. Then it deletes them from the...
spring,unit-testing,mocking,mockito,spring-test
You have to add the @Autowired annotation to service object so that all other attributes in service are injected normally and mocked objects are injected for mocked types. In the example below, normal bean of Class2 will be injected in service, but the @InjectMocks annotation will inject the mocked object...
As stated in the Javadoc, @IfProfileValue is used to indicate that a test is enabled for a specific testing profile or environment. Whereas, @ActiveProfiles is used to declare which active bean definition profiles should be used when loading an ApplicationContext for test classes. In other words, you use @IfProfileValue to...
spring,spring-mvc,multipartform-data,spring-test,spring-mvc-test
The issue is a very small one - just change your CommonsMultipartFile to MultipartFile and your test should run through cleanly. The reason for this issue is the mock file upload parameter that is created is a MockMultipartFile which cannot be cast to the more specific CommonsMultipartFile type....
spring-mvc,mockito,spring-test,spring-test-mvc
My guess is the reason for this difference is because in production you have configured your ViewResolver to use "/WEB-INF/" and possibly a suffix. In your standalone test setup you are not adding a ViewResolver so the default simply takes the view name and turns it into a path, at...
Since springcontext.xml is explicitly setting the injectedString property, there's no reason to annotate the field with @Autowired. I'm not sure why it works in one context but not the other. Could be a difference in the behavior of ClassPathXmlApplicationContext (used in the main method) and GenericApplicationContext (used by the test...
Instead of using @RunWith(SpringJUnit4ClassRunner.class), you need to extend your test class from AbstractTransactionalTestNGSpringContextTests Read here for more info in Spring Reference docs....
java,spring,unit-testing,junit,spring-test
You got it. Most of the time, you don't create a Stub class explicitely though, but use a mocking framework like Mockito which creates it, dynamically, for you. For example: AccountRepository stub = mock(AccountRepository.class); authenticator = new AuthenticatorImpl(stub); when(stub.getAccount("lisa")).thenReturn(new Account(“lisa”, “secret”)); ...
From the Transaction management for @Sql section of the Spring Reference Manual: If the algorithms used by SqlScriptsTestExecutionListener to detect a DataSource and PlatformTransactionManager and infer the transaction semantics do not suit your needs, you may specify explicit names via the dataSource and transactionManager attributes of @SqlConfig. For example: @SqlGroup({...
java,spring,testing,datasource,spring-test
You can use Mockito framework. Using Springockito you can mock your datasources on a Spring environment. Credit of this resource is for kubek2k in this SO answer....
java,unit-testing,junit,mockito,spring-test
As you suggested, Mockito would be a classic tool for such a usecase: // Initialization - should probably be in the @Before method: A a = Mockito.spy(new A()); Mockito.doThrow(new SomeException("yay!")).when(a).m2(); // Actual test: SomeResult actualResult = a.m1(); assertEquals(someExpectedResult, actualResult); // or some other assertion The above snippet creates a spyied...
spring,unit-testing,spring-test,bitronix
Without seeing your exact configuration for the PoolingDataSource, I cannot know exactly how to solve your issue. However, it appears that you can likely solve this issue by creating your PoolingDataSource with a unique name by invoking the setUniqueName() method (in an @Bean method if you're using Java config) or...
The pattern you are using is in fact an anti-pattern: you are coupling your code to legacy constructs, implementation details, etc. And that goes against the principles of Dependency Injection (DI) and Inversion of Control (IoC). Spring, on the other hand, is a proponent of DI and IoC. Thus a...
java,sql,spring,dbunit,spring-test
There isn't currently an annotation that you can use but you might be able to create a subclass of DbUnitTestExecutionListener and add custom logic in the beforeTestMethod. Alternatively you might get away with creating your own TestExecutionListener and just ordering it before DbUnitTestExecutionListener. Another, potentially better solution would be to...
If you need a sequence in your test database, just create it. Also, make sure you have the correct database dialect configured with Hibernate. Consult the following related questions for details: Syntax issue with HSQL sequence: `NEXTVAL` instead of `NEXT VALUE` SequenceGenerator problem with unit testing in Hsqldb/H2 "correct" way...
spring,scala,spring-mvc,spring-test
In your context configuration I don't see that you have a context loader listed. The AnnotationConfigWebContextLoader will locate instances of WebApplicationInitializer on your classpath, by adding this and removing the intializers (which, as you have noted, are for ApplicationContextInitializers and not WebApplicationInitializers) then you should be all set. @RunWith(classOf[SpringJUnit4ClassRunner]) @WebAppConfiguration...
java,spring,spring-mvc,spring-boot,spring-test
Specifying custom configuration yields the expected behaviour. @Configuration @EnableAutoConfiguration(exclude={ SecurityAutoConfiguration.class, ManagementSecurityAutoConfiguration.class, DataSourceAutoConfiguration.class }) @EnableJpaRepositories(basePackages = "com.example.repository") public class TestConfig { @Bean public String sharedSecret() { return null; } @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.HSQL) .build(); } } If anyone from Pivotal reads this (does Dave Syer have...
java,spring,spring-boot,spring-data,spring-test
You are trying to define ClientServiceImpl as a bean twice, once with @Bean method in config class, and once with @Service annotation in the class itself (the later will be picked up by component scanning triggered by @SpringBootApplication). So either add the @Autowired annotation as suggested by iamiddy to use...
java,testing,mocking,mockito,spring-test
To expand on Paweł's correct answer, it's passing because you're coincidentally using one matcher when matching a one-argument method on a mock, which is why the behavior is inconsistent. When you write: verify(commandGatewayMock, times(1)) .send( new CreateEventProposalCommand( any(EventProposalId.class), eventProposalName, EventDescription.of(eventDescription), minimalInterestThreshold ) ); ...Mockito actually matches as if it were:...
If you are using Spring, pleeeeease do not write boilerplate JDBC code. Instead, use Spring's JdbcTemplate which automatically works with the current Spring-managed transaction and eliminates all boilerplate JDBC code. You should replace your entire DAO implementation with something like this: public class JdbcUserDAO { private static final String TERM_USER_SQL...
You can use Springockito to add mocked service implementations to your test application context. <?xml version="1.0" encoding="UTF-8" standalone="no"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mockito="http://www.mockito.org/spring/mockito" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd...
java,testing,junit,configuration,spring-test
From the Spring Docs: Prior to Spring 3.1, only path-based resource locations were supported. As of Spring 3.1, context loaders may choose to support either path-based or class-based resources. As of Spring 4.0.4, context loaders may choose to support path-based and class-based resources simultaneously. However, with spring-test there is a...
unit-testing,junit,spring-test
Try running your tests in your IDE with 'Coverage'. In intelliJ, When you right click on your test folder, you get an option to "Run 'All Tests' with coverage" and it gives you a report on your test coverage. As far as I know, eclipse has something similar as well....
junit,apache-camel,spring-test
You can solve this by adding a setter in you class A. The application context will be loaded and A's B object will be injected by the bean declared in the XML but you can still override it with a mock of B by calling the newly defined setter in...