Testing Spring Boot rest controller, unable to locate package for is() - spring-boot

I'm writing a test for a REST controller in Spring Boot. Is uses is(), but my IDE is not suggesting what package this is in so I'm unable to find it.
Here's my test method;
#Test
public void printerIsReady() throws Exception {
/* Set the contents of status.txt to anything other than 3 */
String statusFilePath = printerPath + "/status.txt";
PrinterFileHelper.writeToFile("5", statusFilePath);
this.mockMvc.perform(get("/printer"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status", is("READY")));
}
I'm finding a lot of examples online that use the is() method, but it's not clear at all what package I need to be adding in order to access it.

I found the answer here How to check String in response body with mockMvc
The package you need to import is;
import static org.hamcrest.Matchers.*;
I needed to add the package to my pom.xml file
<dependency>
<groupId>org.testinfected.hamcrest-matchers</groupId>
<artifactId>core-matchers</artifactId>
<version>1.5</version>
</dependency>

Related

In what package is now located the .csrf() method in Spring 5?

I am trying to write an IT.
mockMvc.perform( post( "/my_endpoint" )
.contentType( MediaType.APPLICATION_JSON )
.header("Authorization", my_credentials)
.with(csrf())
.content( jsonPayload )
)
.andExpect( status().isOk() );
I need to import the csrf() static method, but the package where usually was founded (org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors...) no longer exists.
Some fresh idea on how can I write a csrf protection to avoid a 403 on the test?
Thanks.
To use the Spring Security test support, you must include spring-security-test-5.1.2.RELEASE.jar as a dependency of your project.
And give a try below:-
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProce ssors.*;
mvc.perform(post("/").with(csrf()))
or,
mvc.perform(post("/").with(csrf().asHeader()))
or,
mvc.perform(post("/").with(csrf().useInvalidToken()))
You can use it as follows
csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
My answer is based on the Spring Reactive. Spring Boot :2.6.1
Add below entry in build.gradle
testImplementation 'org.springframework.security:spring-security-test'
And then, csrf() method will be available from below import
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf;

I am getting a compile time error when trying to implement the hateos , It is not showing me the methodOn method

I am trying to implement the Hateoas using spring boot.
In my UserController class i have used the below code
#GetMapping("/users/{id}")
public Resource<User> retrieveUser(#PathVariable int id) {
User user = service.findOne(id);
Resource<User> resource = new Resource<User>(user);
ControllerLinkBuilder linkTo=linkTo(methodOn(this.getClass()).retrieveAllUsers());
I am getting a compile time error on line where i am using the - methodOn().
Compiler is not able to find the methodOn using the controller link builder.
I have used the below import to implement hateoas
import org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
Methods you are using here are static, so to use them you need access using class reference unless you import them using static imports. See more details here

Spring-Hateoas: exception in creating a new link

Overview:
I am going to add a new link based on Spring-Hateoas-Doc to the JSON response by using the following command:
linkTo(methodOn(ProductRepository.class).findOne(10L)).withRel("product");
Problem:
However I got the following exception:
java.lang.IllegalArgumentException: 'uriTemplate' must not be null
So I would be grateful if anyone could suggest me a genuine solution.
I found the issue. As I my processor class is not a rest controller, this issue has been raised.
To solve it , I used the entityLinks instead, as follows:
#Controller
public class StockMovementsProcessor implements ResourceProcessor<Resource<StockMovementsProjection>> {
#Autowired
private EntityLinks entityLinks;
#Override
public Resource<StockMovementsProjection> process(Resource<StockMovementsProjection> stockMovementsProjectionResource) {
StockMovementsProjection stockMovementsProjection = stockMovementsProjectionResource.getContent();
stockMovementsProjectionResource.add(entityLinks.linkFor(Product.class).slash(10L).withRel("product"));
return stockMovementsProjectionResource;
}
}
And it created the following link for me:
http://localhost/products/10
if you are using hateos version 0.20.0 then try upgrading it to 23 using below maven dependency
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.23.0.RELEASE</version>
</dependency>

Issue with importing JcrTagImpl class in OSGI

I need to import JcrTagImpl class which is located in CQ Day Communique 5 Tagging jar file(com.day.cq.cq-tagging)
Then I tried to add the above jar in my pom.xml's dependency as below then I can import the whole package as com.day.cq.tagging.*;
<dependency>
<groupId>com.day.cq</groupId>
<artifactId>cq-tagging</artifactId>
<version>5.7.18</version>
<scope>provided</scope>
</dependency>
UPDATE:
I need to call getTagID method which is located in com.day.cq.tagging.JcrTagImpl class.
AEM uses com.day.cq.tagging.TagCommandServlet to display the TagID in tagging console. TagCommandServlet is importing JcrTagImpl class and calling getTagID method.
I have my own servlet and I wanted to call getTagID. I could not call directly getTagID of JcrTagImpl implementation since it is not exposed. Can it done by any annotation?Can you please guide me how to call getTagId method.
You are trying to call the implementation directly instead of the service. Generally, the implementation is not exposed and you would have to use the service instead.
I guess, TagManager is available as a Sling Service, using which you can work on Tags. Use #Reference to inject it in your service or use sling.adaptTo() to adapt your resource.
EDIT:
Like i mentioned earlier, you cannot access an implementation class directly, as it wouldn't be exported by the bundle.
However to get the tag ID you can use any of the below methods according to your requirements.
If you have the path to the tag, you can get the resource and adaptTo Tag.class and retrieve the tagID
You can adaptTo TagManager.class from a ResourceResolver object and then resolve the path of the tag to get the Tag object
Use the JcrTagManagerFactory service to obtain the tag manager and then resolve the path of the tag.
#SlingServlet({ //config })
public class MyServlet extends SlingSafeMethodsServlet {
#Reference
private JcrTagManagerFactory jcrTagManagerFactory;
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse res) {
//First Method
ResourceResolver resolver = req.getResourceResolver();
Resource tagResource = resolver.resolve("<<path to the tag>>");
Tag tag1 = tagResource.adaptTo(Tag.class);
tag1.getTagID();
//Second Method
TagManager tagManager = resolver.adaptTo(TagManager.class);
Tag tag2 = tagManager.resolve("<<path to tag>>");
tag2.getTagID();
//Third Approach
Session session = resolver.adaptTo(Session.class);
TagManager tagManager = jcrTagManagerFactory.getTagManager(session);
Tag tag3 = tagManager.resolve("<<path to tag>>");
tag3.getTagID();
}
}
Using the TagManager, you can fetch the tags set on the current resource or query for tags etc.

JUnit test: null pointer exception

I am using Spring with EXT JS and hibernate to populate a EXT JS form on a webpage using tomcat... I have the table populating using a method that accesses the database and returns my HQL statement
Now i am trying to execute a simple JUnit test to count the number of records returned but when i am calling the method in the JUint test that populates the EXT JS form, it returns this excception... I dont know why
JUnit Test class
package com.fexco.helloworld.web;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.fexco.helloworld.web.dao.CustomerDaoImpl;
import com.fexco.helloworld.web.model.Customer;
/**
* Unit test for simple App.
* /
public class CustomerServiceTest {
#Autowired
private CustomerDaoImpl customerDaoImpl;
#Test
public void findAllCustomersTest() {
List<Customer> list = customerDaoImpl.findAllCustomers();
int numberInDatabase = list.size();
assertEquals(5, numberInDatabase);
}
}
my method accessing the database
public List<Customer> findAllCustomers(){
List<Customer> list = getHibernateTemplate().find("from Customer");
return list;
}
and my method calling the method accessing the database
public List<Customer> returnAllCustomers(){
List<Customer> list = customerDaoImpl.findAllCustomers();
return list;
}
you can see here that the form is populated with items from the database using the same method as in junit(findAllCustomers())
Does anybody have any ideas?
Add following line before class CustomerServiceTest
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/main/resources/app-context.xml" })
public class CustomerServiceTest {....
Where src/main/resources/app-context.xml - is path to your application context. Its good, to create separate context for tests.
EDIT
You also need to have spring-test.jar in the classpath.
Dependency for maven:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
You did not load your Spring context in your unit test.
you can take a look at the Spring documentation here : http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/testing.html
And an example : Spring: JUnit-Test: applicationContext is not loaded

Resources