I have a JSF-Project with one class called Label and one xhtml-page, called label.xhtml. In label.xhtml the method Label.getValue() is called via injection. The test LabelTest runs a embedded container and in a test method label.xhtml is requested and the body content will be checked. So far everything is fine, but I would like to change the value of the attribute Label.value in my test so the test can assert his own set value and not the value of the Postconstruct-method of class Label.
I put a breakpoint in the constructor of class Label. So I can see the stacktrace and I read the code of many of these methods. Maybe it is possible to change the produces class, so I can put there my own AbstractProducer in some way?
Stacktrace Label constructor
Code on GitHub or scroll down.
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
#Named
#RequestScoped
public class Label {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#PostConstruct
public void fillValue() {
setValue("HELLO");
}
}
import org.apache.tomee.embedded.EmbeddedTomEEContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import javax.ejb.embeddable.EJBContainer;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class LabelTest {
private WebDriver driver;
#Before
public void setup() {
driver = new HtmlUnitDriver();
Map<Object, Object> properties = new HashMap();
properties.put(EJBContainer.PROVIDER, EmbeddedTomEEContainer.class);
properties.put(EJBContainer.MODULES, new File[]{new File("src/main/webapp/")});
properties.put(EJBContainer.APP_NAME, "hfe");
System.setProperty("tomee.webapp.externalRepositories", "build/classes/main,build/classes/test");
EmbeddedTomEEContainer.createEJBContainer(properties);
}
#After
public void cleanup() {
driver.close();
}
#Test
public void requestHtmlPage_ThenBodyContainsPostConstructValue() {
assertEquals("HELLO", getBodyValue());
}
#Test
public void manipulateInjectedObjectAndRequestHtmlPage_ThenBodyContainsValueOfManipulatedInjectedObject() {
// how is it possible to manipulate the injected object with value=MY_VALUE?
assertEquals("MY_VALUE", getBodyValue());
}
private String getBodyValue() {
driver.get("http://localhost:8080/hfe/faces/label.xhtml");
WebElement body = driver.findElement(By.tagName("body"));
return body.getText();
}
}
label.xhtml
<html>
<h:body>
#{label.value}
</h:body>
</html>
I got a solution from the TomEE User MailingList: Using the Annotation #Specializes or using a ServletFilter. You can find the example code at the GitHub project.
Related
How will the Lambda handler of multiple different types of trigger look like in java?
I want to set a trigger for Cloudwatch Event Rule, S3. How can I do this?
public class App implements RequestHandler<S3Event, Context>
{
public Context handleRequest(S3Event s3event, Context context) {
System.out.println("welcome to lambda");
}
}
You can use Map<String,String> as input
public class Handler implements RequestHandler<Map<String,String>, String>{
#Override
public String handleRequest(Map<String,String> event, Context context) {
}
}
Or use RequestStreamHandler and parse the InputStream to the correct object.
public class HandlerStream implements RequestStreamHandler {
#Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
}
}
using a generic Object could work, I use Serverless Framework with:
package com.serverless;
import java.util.Collections;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class Handler implements RequestHandler<Object, Object> {
private static final Logger LOG = LogManager.getLogger(Handler.class);
#Override
public Object handleRequest(final Object input, final Context context) {
LOG.info("received: {}", input);
return input;
}
}
I am writing JUnit Test case with Mockito for a class which has two methods methodA,methodB. I would like to mock the call to the methodA from methodB in my test case.Some one help me.pls
Here is the class:
public Class Test{
public static List<Object> methodA() {
...
return list;
}
public static List<Object> methodB() {
...
list = methodA();
return list;
}
}
You will need to use PowerMockito to mock the static method.
Example:
package unitest;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(unitest.Test.class)
public class TestTest {
#Test
public void testMethodB() {
PowerMockito.mockStatic(unitest.Test.class);
PowerMockito.when(unitest.Test.methodA()).thenReturn(new ArrayList());
List b = unitest.Test.methodB();
org.junit.Assert.assertNotNull(b);
}
}
I am trying to create a mock data for Dao class. Test case is running successfully but it is returning null data. I searched and implemented #Mock, #InjectMocks, Inititated MockitoAnnotation but still it is not working. The project is in spring. Context path is also correct. I have not used any other methods. First for running I am trying to just call a method and print. Please help me to solve this error.
RegionManager Class:
#Service("regionManager")
public class RegionManager implements RegionManagerIntf {
#Autowired
RegionDaoIntf regionInquiry;
private RegionDao regionDao;
#Override
public ListPojo retrieveData(String Id, String details, String code) {
return regionInquiry.retrievePData(Id, details, code);
}
public RegionDao getRegionDao() {
return regionDao;
}
public void setRegionDao(RegionDao regionDao) {
this.regionDao = regionDao;
}
}
Dao Class:
#Component
public class RegionProcessorFactory implements RegionProcessorIntf {
private static final Logger logger = Logger
.getLogger(RegionProcessorFactory.class);
#Override
public ListPojo retrieveData(String Id,
String details, String code) {
ListPojo listPojo = new ListPojo();
//Do some action
return listPojo;
}
}
ListPojo:
It contains getter setters.
Test Class:
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.context.ContextConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
#RunWith(MockitoJUnitRunner.class)
#ContextConfiguration({"classpath*:spring/beanRefContext.xml"})
public class RegionManagerTest
{
private String Id = "12345";
private String Code = "123";
private String details = "12";
ObjectMapper mapper;
#Mock
private RegionProcessorFactory dao;
#Mock
private ListPojo listPojo;
#InjectMocks
private RegionManager service;
/**
* Before method will be called before executing every test case
*/
#Before
public void initialize() {
System.out.println("In initialize");
MockitoAnnotations.initMocks(this);
dao = mock(RegionProcessorFactory.class);
listPojo = mock(ListPojo.class);
service = new RegionManager();
service.setRegionDao(dao);
}
#Test
public void CreateDatabaseMock() throws Exception
{
System.out.println("dao result :: "+dao.retrieveData(Id, "", ""));
when(dao.retrieveData(Id, "", "")).thenReturn(listPojo);
verify(dao).retrieveData(Id, "", "");
}
/**
* After method will be called after executing every test case
*/
#After
public void TearDownClass() {
}
}
First: If you are using #RunWith(MockitoJUnitRunner.class) there is no need for MockitoAnnotations.initMocks(this); more on that here
Second: Everything with #Mock will be mocked and mockito will try to inject it into object annotated with #InjectMocks which mockito will instantiate(in old mockito versions you had to create the object yourself) so following lines are not needed:
dao = mock(RegionProcessorFactory.class);
listPojo = mock(ListPojo.class);
service = new RegionManager();
service.setRegionDao(dao);
Third: The actual execution should come after stubbing
#Test
public void CreateDatabaseMock() throws Exception{
when(dao.retrieveData(Id, "", "")).thenReturn(listPojo);
System.out.println("dao result :: "+dao.retrieveData(Id, "", ""));
verify(dao).retrieveData(Id, "", "");
}
I would like to test the behaviour configured by my Katharsis ResourceRepository (katharsis-spring 2.1.7):
import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.ResourceRepository;
import org.springframework.stereotype.Component;
#Component
public class UserResourceRepository implements ResourceRepository<UserDTO, String> {
#Autowired
private UserRepository databaseRepository;
#Override
public UserDTO findOne(String email, QueryParams queryParams) {
return null;
}
#Override
public Iterable<UserDTO> findAll(QueryParams queryParams) {
return null;
}
#Override
public Iterable<UserDTO> findAll(Iterable<String> iterable, QueryParams queryParams) {
return null;
}
#Override
public void delete(String email) {
}
#Override
public UserDTO save(UserDTO s) {
return null;
}
}
I would like to test it in a similar way as I do it with normal, Spring Controllers, using Mockito to mock database repository and using MockMvc:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.Optional;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(MockitoJUnitRunner.class)
public class UserJsonApiTest {
#InjectMocks
private UserResourceRepository resourceRepository;
#Mock
private UserRepository databaseRepository;
private MockMvc mockMvc;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(resourceRepository).build();
}
#Test
public void first() throws Exception {
Optional<UserEntity> user = Optional.of(new UserEntity().
id(1).
email("test#test").
firstName("test first name").
lastName("test last name").
pass("test pass"));
when(
databaseRepository.
findOneByEmail(user.get().getEmail())).
thenReturn(user);
mockMvc.perform(
get("/users/" + user.get().email())).
andExpect(status().isOk())
;
}
}
Obviously, this code doesn't work because my Katharsis UserResourceRepository is not really a Controller. So far I have learned (from logs) that it is actually using some filters mappings and class named io.katharsis.spring.KatharsisFilterV2.
Is there any way to use MockMvc for such test? If not - is there any other way I could test it without starting the whole server (with mocking)?
You could use an embedded Server - like UndertowJaxrsServer - and inject the KatharsisFeature:
Create a class (MyApp) which extends Application public static class MyApp extends Application { and deploy it to the embedded server server.deploy(MyApp.class);
in this Class, overwrite getClasses and add a second class (KatharsisFeatureTest) which implements Feature KatharsisFeatureTest implements Feature
in KatharsisFeatureTest you can then register a KatharsisFeature and there you can overwrite JsonServiceLocator and inject the mock.
Sound a little bit complicated, but works like charm :)
Have a look at my implementation.
.
#RunWith(MockitoJUnitRunner.class)
public class EndpointResourceTest {
#Mock
private EndpointService endpointService;
#InjectMocks
private final static EndpointResourceV1 endpointRessource = new EndpointResourceV1();
private static UndertowJaxrsServer server;
#BeforeClass
public static void beforeClass() throws Exception {
server = new UndertowJaxrsServer();
server.deploy(MyApp.class);
server.start();
}
#Test
public void testGetEndpoint() throws URISyntaxException {
Mockito.when(endpointService.getEndpoint("SUBMIT")).thenReturn(new EndpointDTO("SUBMIT", "a", "b"));
Client client = ClientBuilder.newClient();
Response response = client.target(TestPortProvider.generateURL("/api/endpoints/SUBMIT"))
.request(JsonApiMediaType.APPLICATION_JSON_API)
.get();
Assert.assertEquals(200, response.getStatus());
String json = response.readEntity(String.class);
Assert.assertTrue(json.contains("SUBMIT"));
Assert.assertTrue(json.contains("a"));
Assert.assertTrue(json.contains("b"));
Mockito.verify(endpointService, Mockito.times(1)).getEndpoint("SUBMIT");
}
#AfterClass
public static void afterClass() throws Exception {
server.stop();
}
#ApplicationPath("/api")
public static class MyApp extends Application {
#Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> classes = new HashSet<Class<?>>();
classes.add(KatharsisFeatureTest.class);
return classes;
}
}
public static class KatharsisFeatureTest implements Feature {
#Override
public boolean configure(FeatureContext featureContext) {
featureContext
.property(KatharsisProperties.RESOURCE_SEARCH_PACKAGE, "...")
.register(new io.katharsis.rs.KatharsisFeature(
new ObjectMapper(), new QueryParamsBuilder(new DefaultQueryParamsParser()), new SampleJsonServiceLocator() {
#Override
public <T> T getInstance(Class<T> clazz) {
try {
if (clazz.equals(EndpointResourceV1.class)) {
return (T) endpointRessource;
}
return clazz.newInstance();
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}));
return true;
}
}
}
I have worked with Jax WS and had used wsgen and wsimport for auto marshalling of custom types. Can I use wsgen with JaxRS as well? If so where should I place my wsgen generated files and how to reference them? I just wish not to deal with using JAXB myself and use wsgen as a shortcut.
By default a JAX-RS implementation will use JAXB to convert domain objects to/from XML for the application/xml media type. In the example below a JAXBContext will be created on the Customer class since it appears as a parameter and/or return type in the RESTful operations.
package org.example;
import java.util.List;
import javax.ejb.*;
import javax.persistence.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
#Stateless
#LocalBean
#Path("/customers")
public class CustomerService {
#PersistenceContext(unitName="CustomerService",
type=PersistenceContextType.TRANSACTION)
EntityManager entityManager;
#POST
#Consumes(MediaType.APPLICATION_XML)
public void create(Customer customer) {
entityManager.persist(customer);
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("{id}")
public Customer read(#PathParam("id") long id) {
return entityManager.find(Customer.class, id);
}
}
The JAXBContext created on a single class will also create metadata for all transitively reference classes but that may not bring in everything that was generated from your XML schema. You will need to leverage the JAX-RS context resolver mechanism.
package org.example;
import java.util.*;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
#Provider
#Produces("application/xml")
public class CustomerContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext jc;
public CustomerContextResolver() {
try {
jc = JAXBContext.newInstance("com.example.customer" , Customer.class.getClassLoader());
} catch(JAXBException e) {
throw new RuntimeException(e);
}
}
public JAXBContext getContext(Class<?> clazz) {
if(Customer.class == clazz) {
return jc;
}
return null;
}
}