I have a Sample Grails Service and trying to auto wire it inside integration test of Grails. All though the IntelliJ editor shows its auto-wired, but at runtime I always get it as null.
Integration Test is as below where I sampleService as always null.
class Sample {
def sampleService;
#Test
public void testSample() {
println(" Hello...")
}
}
After adding #Autowired explicitly to my service resolved the issue. Refer the code below
class Sample {
#Autowired
def sampleService;
#Test
public void testSample(){
println(" Hello...")
}
}
Related
I want to write some kind of unit test which depends on Spring Security.
For example, I have some service method which uses some repository and marked with #PreAuthorize annotation. Repository I can mock with Mockito, there is no problem. Also I can mock Security Context by #WithSecurityContext annotation. But when I run test, the #PreAuthorize annotation is just ignored. Of course I can run that test with #SpringBootTest annotation as an integration test and in this case the Security Context is up but this way is heavy and slow.
Is there a way to run unit test with only Spring Security Context raised?
UPDATE
Made an example of such kind of test. Thanks to #Sam Brannen for giving right direction.
#ActiveProfiles("method-security-test")
#RunWith(SpringRunner.class)
#SpringBootTest(classes = {ExampleService.class, ExampleServiceTest.MethodSecurityConfiguration.class})
public class ExampleServiceTest {
private ExampleService service;
#Autowired
public void setService(ExampleService service) {
this.service = service;
}
#Test
#WithMockUser(username = "john_doe")
public void testAuthenticated() {
String actualMessage = service.example();
Assert.assertEquals("Message of john_doe", actualMessage);
}
#Test(expected = AuthenticationException.class)
public void testNotAuthenticated() {
service.example();
Assert.fail();
}
#TestConfiguration
#EnableGlobalMethodSecurity(prePostEnabled = true)
static class MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
}
}
#Service
class ExampleService {
#PreAuthorize("isAuthenticated()")
String example() {
Principal principal = SecurityContextHolder.getContext().getAuthentication();
return "Message of " + principal.getName();
}
The #PreAuthorize annotation from Spring Security will only be honored if Spring Security proxies your component (e.g., service bean).
The simplest way to make that happen is by annotating an #Configuration class with #EnableGlobalMethodSecurity(prePostEnabled = true), having your component registered as a bean (e.g., via component scanning or an #Bean method), and including your AuthenticationManager setup.
You can then create a focused integration test using #ContextConfiguration (without Spring Boot testing support) to load an ApplicationContext from your #Configuration class. And you can use #Autowired to get access to your proxied component which will be advised with the #PreAuthorize security check support.
You might find this old blog post useful as well for background information: https://spring.io/blog/2013/07/04/spring-security-java-config-preview-method-security/
In my current setup i want to unit test a Grails service that has an #autowired dependency and inject a mock for the dependency.
class AcmeService {
#Autowired
FooService fooService // not a Grails service!
}
The FooService is not a Grails service but it is a dynamic implementation from a FeignClient. I am looking for a way to inject a Mock for the FooService service in a UnitTest. What would be the best solution to do this?
I tried setting the dependency in the setup, but then i get a 'Unsatisfied dependency expressed through field fooService'
class AcmeService extends Specification {
FooService mockedFooService = Mock(FooService)
def setup() {
service.fooService = mockedFooService
}
}
you can add the following to your unit test:
def doWithSpring = {
fooService( InstanceFactoryBean, Mock(FooService) )
}
I'm having some trouble testing a Spring Boot application with MockMvc.
I have the following test class:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {SpringConfiguration.class, SecurityConfiguration.class})
#IntegrationTest({"server.port=8080"})
#WebAppConfiguration
public class DemoTest {
#Autowired
private EmbeddedWebApplicationContext webApplicationContext;
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void testGetAccountUnauthenticated() throws Exception {
mockMvc.perform(get("/accounts/1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
}
}
This results in a HTTP 200 not a 401. I have component scanning and autoconfiguration enabled and spring security is configured in my SecuityConfiguration class as follows:
#Configuration
#EnableWebSecurity
#EnableWebMvcSecurity // required for use of #AuthenticationPrincipal in MVC controllers.
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) {
web.debug(true);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//set up authentication.
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
// set up form login
}
}
If I use a RestTemplate to access http://localhost:8080/accounts/1 then I get the expected behaviour (HTTP 401).
I have seen other examples (e.g. Spring Boot setup security for testing) that suggest that I autowire the FilterChainProxy and add the filter manually using the WebApplicationContext.addFilters(filterChainProxy) method. However, this actually fails for me (org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.web.FilterChainProxy] found).
I have two questions:
Why does the injected WebApplicationContext not automatically use the SpringSecurity filters? Even if I could get the FilterChainProxy and add it manually, the JavaDoc for EmbeddedWebApplicationContext states
any {#link Servlet} or {#link Filter} beans defined in the context will be automatically registered with the embedded Servlet container
As a result I wouldn't expect to have to manually add the security filter chain since I (incorrectly?) expect this to "just work" due to the Auto Configuration magic in Spring Boot?
Why is there no FilterChainProxy in the application context? Again, perhaps my expectations of the AutoConfiguration is incorrect - but I thought that this would be configured as part of the context configuration.
Thanks in advance for any advice.
Edits
The reason a FilterChainProxy doesn't get injected was because I has my configuration set to
public void configure(WebSecurity web) {
web.debug(true);
}
This actually configures a org.springframework.security.web.debug.DebugFilter instead. The way I have now managed to get the Filter regardless of this debug setting is as follows:
#Resource(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
private Filter securityFilter;
If I add this to the MockMvcBuilder as follows:
MockMvcBuilders.webAppContextSetup(webApplicationContext).addFilters(securityFilter)
then it does work as expected.
But, I don't understand why MockMVC would ignore the filters as this seems important for testing a request since anything could happen in a Filter that might impact the outcome of the test. Furthermore, it means that to test properly I'd need to lookup all Filters in the servlet context and establish their priority/url mapping and add them appropriately. This seems error prone and unnecessary.
I agree that MockMVC is perhaps more for testing SpringMVC and custom code in controllers, as commented by #dave-syer. So in cases when one wants to test spring MVC infrastructure with your custom controller code at the same time (correctness of controllers mapped to URLs; mapping and validation of input and output objects; standard controllers; your controllers) without leveraging the Servlet container part of the stack, MockMVC is there for you.
But MockMVC also does have methods to add filters, so it is designed with a possibility to engage Filters in the described type of testing. Sometimes filter may play functional role for code inside of a controller and that would be otherwise not testable with MockMVC.
With all that theory in mind I was trying to mimic Boot behaviour for my tests where filters would be set up in Spring Boot way and picked up by my tests to be used with MockVMC. Here is a snippet that I ended up using. It can surely be enhanced to mimic Boot behaviour in more precisely and extracted to some custom MockMVCBuilder.
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setUp() {
Collection<Filter> filterCollection = wac.getBeansOfType(Filter.class).values();
Filter[] filters = filterCollection.toArray(new Filter[filterCollection.size()]);
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(filters).build();
}
Have you tried this?
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
...
#Slf4j
#RunWith(SpringRunner.class)
#SpringBootTest
public class AuthorizeTest {
#Autowired
private WebApplicationContext wac;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.apply(springSecurity())
.build();
}
...
}
In my case it is 403, not 401, but you get the idea.
I need to write Unit tests for production routes in Grails which use Services referenced by Camel bean component. My requirement is neither to change nor to copy existing routes in test.
Problem is to somehow mock Service bean and add it to Camel registry.
I was able to do this using 'bind' method on 'context.registry.registry' object. Is there any functionality to do that in more safe way? Camel version is 2.10, Grails 2.1
Route is:
from('direct:validate').to('bean:camelService?method=echo')
CamelService is just simple class:
package com
class CamelService {
def echo(text) {
println "text=$text"
text
}
}
Test is following (route copied only to make question simpler):
package com
import grails.test.mixin.*
import org.apache.camel.builder.RouteBuilder
import org.apache.camel.test.junit4.CamelTestSupport
#TestFor(CamelService)
class RouteTests extends CamelTestSupport {
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from('direct:validate').to('bean:camelService?method=echo')
}
};
}
void testMockBean() throws Exception {
context.registry.registry.bind 'camelService', service
def result = template.requestBody('direct:validate', 'message')
assert result != null
assert result == 'message'
}
}
Camel allows you to plugin any custom registry you want, and out of the box it uses a Jndi based registry, which is why you can bind a service to it with the code example. An alternative is to use a SimpleRegistry which is just a Map, so you can put a service into the registry using the put method from the Map. You would then need to override createCamelContext method from the CamelTestSupport class and
pass in the SimpleRegistry to the constructor of DefaultCamelContext.
Anyway your code is safe as long you use the non-Spring CamelTestSupport class, as its using the JNDI based registrry out of the box. If you use CamelSpringTestSupport, then its a spring based registry, and you would need to use the spring app context to add your bean to it.
You can inject your components using CamelSpringtestSupport rather than CamelTestSupport as your base class.
Reading the documentation on Spring Test will help you for sure, and you might find interesting to use mock in your tests.
Anyway, you can build a custom context for your test, containing your bean's declaration and load it in the test.
public class RouteTests extends CamelSpringTestSupport {
#Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("route-test-context.xml");
}
#Test
public void testMockBean(){
//...
}
}
route-test-context.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cxf="http://camel.apache.org/schema/cxf" xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="service" ref="com.CamelService"/>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<package>com</package>
</camelContext>
</beans>
I am having problems integration testing my Grails service because the service under test is not being injected in to my test. I have followed the advice from answers to questions else where on Stackoverflow but as yet can not get my service injected. The following class is under /<project_root>/test/integration/com/example:
package com.example
import grails.test.GrailsUnitTestCase
class MyServiceIntegrationTest extends GroovyTestCase {
MyService service;
public void testService() {
assert service != null
}
}
I have tried executing both from the command-line (grails test-app) and from within IDEA both result in the same failure, namely service is null
This is Grails 1.3.6
Any suggestions on how to get my integration test working please?
Autowiring works the same way in integration tests as in other parts of the framework, so you need to make sure the property is named like the service except with the appropriate unCamelCase.
class MyServiceIntegrationTest extends GroovyTestCase {
def myService
}
Assuming your service is an object named MyService.