Menu
  • HOME
  • TAGS

What are the benefits of Spring Testing in terms of testing web services?

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-test, groovy library and qualifier tag incompatibility

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...

Spring-test unexpectedly fails, how best triangulate the error?

java,spring-3,spring-test

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...

Spring integration testing without XML

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....

Spring JUnit Test not loading full Application Context

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...

Failed to load properties from junit spring

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")) ...

JUnit Tests: Why is Maven (Surefire) so much slower than running on Eclipse?

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...

SpringJUnit4ClassRunner unit test does not work. Error: Failed to load ApplicationContext

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 boot application fails on mockmvc test

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...

reuse cached spring contexts to build a bigger context

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...

How to create session in Spring Junit

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 =...

Disable security for unit tests with spring boot

spring-boot,spring-test

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...

Test XML content without using mock mvc

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 MockMVC - How to mock custom validators running outside of controllers

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...

Testing spring controllers and setting up Junit test

spring-test

You need to include the necessary static imports. See the Static Imports section of the Spring Reference Manual for details....

What embedded database to use for seamless MySQL > (embedded database) dumping

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...

MockHttpServletRequest ignoring set fields, how do I get around this?

java,servlets,spring-test

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...

Why is TestContext.getInstance() is null in beforeTestClass and afterTestClass methods in TestExecutionListener?

java,testng,spring-test

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 Testing: How to enable auto-scan of beans

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...

Defining a spring active profile within a test use case

java,spring,spring-test

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...

Why in Spring JUnit test a new ApplicationContext is initialized and created for each test method? [closed]

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...

Could not load TestContextBootstrapper - Spring Unit testing

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>...

No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined

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...

Some doubts in a JUnit test Spring example

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....

Spring Mockito TestNG - Mocks persist across tests

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...

Aspect not being called in Spring test

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 MockMvc Passing Nested Form Parameters

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; }...

Integration tests for continuous delivery using docker

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...

Spring Boot Application with DB - Test class fails after context being recreated with @DirtiesContext

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....

Spring-Boot module based integration testing

spring-boot,spring-test

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,...

Why Hibernate re-update when querying objects causes Batch update returned unexpected row count?

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...

Want spring bean to have mocked as well as real implementations+spring+mockito

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...

@IfProfileValue vs @ActiveProfiles in the context of Spring test

spring-test

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...

Test a Spring multipart/form-data controller with uploading of some files

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....

returning null in controller breaks MockMvc

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...

Spring: can't load properties on junit with PropertyPlaceholderConfigurer

java,spring,junit,spring-test

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...

TestNG + Spring test: EntityManager return null with testng

testng,spring-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....

How exactly works Spring JUnit test that uses stubs?

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”)); ...

spring @sqlgroup with multiple datasource

spring-test

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({...

Make a fake javax.sql.DataSource?

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....

JUnit Test : Forcing exception from internal method call

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...

Bitronix + Spring tests + Different spring profiles

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...

Best practice for default property values in spring beans

java,spring,tdd,spring-test

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...

How to do a custom database setup/teardown in Spring Test Dbunit?

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...

how to simulate sequence during DAO layer test

junit,tdd,dao,spring-test

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...

How to run tests using a custom WebApplicationInitializer?

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...

Make Spring Boot Recreate Test Databases

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...

Using @SpringApplicationConfiguration in test throws Exception?

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...

Mockito verify + any behaves unpredictably

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:...

Utilizing Spring transactionManager for integration test

java,spring,spring-test

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...

How to test Spring service beans that themself have autowired dependencies?

java,spring,junit,spring-test

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...

Cannot process locations AND classes for context configuration

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...

Methods which have not been tested in Spring MVC project

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....

Mocking test class Spring camel

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...