My controller code is not reachable from the MockMvc get request and i am always getting 404 - mockito

I am trying to mock my controller and write testcases for it. But when I tried to debug the Test class the control is not getting into my Controller class. I am not sure what I am doing wrong here.
Please help me to resolve this as I am stuck on this for almost more that 3 hours.
My Service class
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bnpp.leavemanagement.dao.DepartmentRepository;
import com.bnpp.leavemanagement.model.DepartmentModel;
#Service
public class DepartmentService
{
#Autowired
DepartmentRepository depRepo;
public List<DepartmentModel> listDepartment = new ArrayList<>();
public List<DepartmentModel> getAllDepartments()
{
List<DepartmentModel> allDepartment = depRepo.findAll();
return allDepartment;
}
public DepartmentModel fetchDepartmentById( int id)
{
DepartmentModel depDetail = null;
try
{
depDetail = depRepo.findById(Long.valueOf(id)).get();
}
catch(Exception ex)
{
depDetail = null;
}
return depDetail;
}
public DepartmentModel addDepartment(DepartmentModel depDetail)
{
DepartmentModel depExists = null;
if (listDepartment.size() > 0)
{
depExists = listDepartment.stream()
.filter(d -> d.getName().equalsIgnoreCase(depDetail.getName()))
.findFirst()
.orElse(null);
}
//Below condition is to restrict duplicate department creation
if(depExists == null)
{
depRepo.save(depDetail);
listDepartment.add(depDetail);
}
else
{
return null;
}
return depDetail;
}
public DepartmentModel updateDepartment(DepartmentModel depDetail)
{
DepartmentModel depUpdate = null;
try
{
depUpdate = depRepo.findById(depDetail.getId()).get();
depUpdate.setName(depDetail.getName());
depRepo.save(depUpdate);
}
catch(Exception ex)
{
depUpdate = null;
}
return depUpdate;
}
public DepartmentModel deleteDepartment(DepartmentModel depDetail)
{
try
{
depRepo.deleteById(depDetail.getId());
}
catch(Exception ex)
{
return null;
}
return depDetail;
}
}
My Test Class
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Description;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.context.WebApplicationContext;
import com.bnpp.leavemanagement.controller.DepartmentController;
import com.bnpp.leavemanagement.model.DepartmentModel;
import com.bnpp.leavemanagement.service.DepartmentService;
#ExtendWith(MockitoExtension.class)
#WebMvcTest(DepartmentController.class)
#ContextConfiguration(classes = com.bnpp.leavemanagementsystem.LeaveManagementSystemApplicationTests.class)
public class DepartmentControllerTest {
#MockBean
DepartmentService depService;
#Autowired
private MockMvc mockMvc;
#InjectMocks
DepartmentController departmentController;
#Autowired
private WebApplicationContext webApplicationContext;
#Test
#Description("Should return a list of DepartmentModel objects when called")
void shouldReturnListOfDepartmentModel() throws Exception
{
DepartmentModel depModel = new DepartmentModel();
depModel.setId(1L);
depModel.setName("Mock");
List<DepartmentModel> listDepmodel = new ArrayList<>();
listDepmodel.add(depModel);
Mockito.when(depService.getAllDepartments()).thenReturn(listDepmodel);
mockMvc.perform(MockMvcRequestBuilders.get("/department"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.size()", Matchers.is(1)))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].id").value(1))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("Mock"));
}
}
My Controller class
package com.bnpp.leavemanagement.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.bnpp.leavemanagement.dao.DepartmentRepository;
import com.bnpp.leavemanagement.model.DepartmentModel;
import com.bnpp.leavemanagement.service.DepartmentService;
#RestController
public class DepartmentController
{
#Autowired
DepartmentService depService;
#GetMapping("/department")
public ResponseEntity<List<DepartmentModel>> getDepartments()
{
List<DepartmentModel> allDepartment = depService.getAllDepartments();
if(allDepartment.size() == 0)
{
return new ResponseEntity( HttpStatus.NOT_FOUND);
}
return new ResponseEntity( allDepartment, HttpStatus.OK);
}
#GetMapping("/department/{id}")
public ResponseEntity<DepartmentModel> fetchDepartmentById(#PathVariable("id") int id)
{
DepartmentModel resDep = depService.fetchDepartmentById(id);
if(resDep == null)
{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
else
{
return new ResponseEntity( resDep, HttpStatus.OK);
}
}
#PostMapping("/department/create")
public ResponseEntity<DepartmentModel> createDepartment(#RequestBody DepartmentModel depNew)
{
DepartmentModel resDep = depService.addDepartment(depNew);
if(resDep == null)
{
return new ResponseEntity(HttpStatus.EXPECTATION_FAILED);
}
else
{
return new ResponseEntity( resDep, HttpStatus.CREATED);
}
}
#PutMapping("/department/update")
public ResponseEntity<DepartmentModel> updateDepartment(#RequestBody DepartmentModel depNew)
{
DepartmentModel resDep = depService.updateDepartment(depNew);
if(resDep == null)
{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
else
{
return new ResponseEntity( resDep, HttpStatus.OK);
}
}
#DeleteMapping("/department/delete")
public ResponseEntity<DepartmentModel> deleteDepartment(#RequestBody DepartmentModel depDel)
{
DepartmentModel resDep = depService.deleteDepartment(depDel);
if(resDep == null)
{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
else
{
return new ResponseEntity(HttpStatus.OK);
}
}
}

The minimal viable test setup to use MockMvc with #WebMvcTest is the following:
#WebMvcTest(DepartmentController.class)
class DepartmentControllerTest {
#MockBean
DepartmentService depService;
#Autowired
private MockMvc mockMvc;
#Test
#Description("Should return a list of DepartmentModel objects when called")
void shouldReturnListOfDepartmentModel() throws Exception {
DepartmentModel depModel = new DepartmentModel();
depModel.setId(1L);
depModel.setName("Mock");
List<DepartmentModel> listDepmodel = new ArrayList<>();
listDepmodel.add(depModel);
Mockito.when(depService.getAllDepartments()).thenReturn(listDepmodel);
mockMvc.perform(MockMvcRequestBuilders.get("/department"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.size()", Matchers.is(1)))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].id").value(1))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("Mock"));
}
}
Explanation:
#InjectMocks is not necessary as with #MockBean you're adding a mocked version of DepartmentService to your Spring TestContext and Spring DI's mechanism will inject it to your DepartmentController
#ExtendWith(SpringExtension.class) is also redundant, as the meta annotation #WebMvcTest already activates the SpringExtension.class
You don't need #ContextConfiguration here as #WebMvcTest takes care to detect your Spring Boot entrypoint class and start a sliced context
If the test still doesn't work, please add all your dependencies, the way you structure your code, and your main Spring Boot class (annotated with #SpringBootApplication).
Further reads that might shed some light on this:
Difference Between #Mock and #MockBean
Guide to Testing Spring Boot Applications With MockMvc

Related

Postman GET request is giving 404 not found in postman for my endpoint http://localhost:8080/employee/all

Can anyone help me in what wrong I am doing in my spring application? I am getting 404 not found for http://localhost:8080/employee/all endpoint.
Postman error -
{
"timestamp": "2023-02-03T10:33:58.409+00:00",
"status": 404,
"error": "Not Found",
"path": "/employee/all"
}
Project Structure
This is the controller class -
package website.sample.employee.management.system;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import website.sample.employee.management.system.model.Employee;
import website.sample.employee.management.system.service.EmployeeService;
#RestController
#RequestMapping("/employee")
public class EmployeeResource {
private final EmployeeService employeeService;
public EmployeeResource(EmployeeService employeeService) {
this.employeeService = employeeService;
}
#GetMapping("/all")
public ResponseEntity<List<Employee>> getAllEmployees() {
List<Employee> employees = employeeService.findAllEmployees();
return new ResponseEntity<>(employees, HttpStatus.OK);
}
#GetMapping("/find/{id}")
public ResponseEntity<Employee> getEmployeeById(#PathVariable("id") Long id) {
Employee employee = employeeService.findEmployeeById(id);
return new ResponseEntity<>(employee, HttpStatus.OK);
}
#PostMapping("/add")
public ResponseEntity<Employee> addEmployee(#RequestBody Employee employee) {
Employee newEmployee = employeeService.addEmployee(employee);
return new ResponseEntity<>(newEmployee, HttpStatus.CREATED);
}
#PutMapping("/update")
public ResponseEntity<Employee> updateEmployee(#RequestBody Employee employee) {
Employee updateEmployee = employeeService.updateEmployee(employee);
return new ResponseEntity<>(updateEmployee, HttpStatus.OK);
}
#DeleteMapping("/delete/{id}")
public ResponseEntity<?> deleteEmployee(#PathVariable("id") Long id) {
employeeService.deleteEmployee(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
EmployeeRepo class -
package website.sample.employee.management.system.repo;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import website.sample.employee.management.system.model.Employee;
public interface EmployeeRepo extends JpaRepository<Employee, Long> {
void deleteEmployeeById(Long id);
Optional<Employee> findEmployeeById(Long id);
}
EmployeeService class -
package website.sample.employee.management.system.service;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import website.sample.employee.management.system.exception.UserNotFoundException;
import website.sample.employee.management.system.model.Employee;
import website.sample.employee.management.system.repo.EmployeeRepo;
#Service
public class EmployeeService {
private final EmployeeRepo employeeRepo;
#Autowired
public EmployeeService(EmployeeRepo employeeRepo) {
this.employeeRepo = employeeRepo;
}
public Employee addEmployee(Employee employee) {
employee.setEmployeeCode(UUID.randomUUID().toString());
return employeeRepo.save(employee);
}
public List<Employee> findAllEmployees() {
return employeeRepo.findAll();
}
public Employee updateEmployee(Employee employee) {
return employeeRepo.save(employee);
}
public Employee findEmployeeById(Long id) {
return employeeRepo.findEmployeeById(id)
.orElseThrow(() -> new UserNotFoundException("User by id " + id + " was not found"));
}
public void deleteEmployee(Long id) {
employeeRepo.deleteEmployeeById(id);
}
}
This is the error I get in postman -
{
"timestamp": "2023-02-03T10:33:58.409+00:00",
"status": 404,
"error": "Not Found",
"path": "/employee/all"
}
I am trying to use the endpoint http://localhost:8080/employee/all
Please let me know if you know why postman is not able to find this end point.
I have tried some ways for this issue on the internet but cannot debug it.

Cucumber testng with PowerMockTestCase to mock static classes

I am using cucumber BDD, testng, java to write some BDD test. I would like to mock static classes in order to write my test. However when I write this testrunner, it fails to initialize the BDD scenarios.
Complete Example(note the commented line PrepareForTest) :
import gherkin.events.PickleEvent;
import io.cucumber.testng.CucumberOptions;
import io.cucumber.testng.PickleEventWrapper;
import io.cucumber.testng.TestNGCucumberRunner;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import static org.mockito.Matchers.any;
#CucumberOptions(
features = {
"src/test/resources/features/sample"
},
glue = {
"com.demo.stepdefinitions.sample"
},
plugin = {
"pretty",
"html:target/cucumber-reports/cucumber-pretty",
"json:target/cucumber-reports/sampple-report.json",
"rerun:target/cucumber-reports/sample-rerun.txt"
}
)
//#PrepareForTest({Util.class})
public class TestngWithDataproviderTest extends PowerMockTestCase {
private TestNGCucumberRunner testNGCucumberRunner;
private void mockActiveBucket() {
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.getBucketId(any(Long.class))).thenReturn(3);
}
#BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
#Test(dataProvider = "users")
public void testMockStatic(String username){
System.out.println("username: " + username);
System.out.println("static test passed");
mockActiveBucket();
Assert.assertTrue(true);
}
#Test(groups = "cucumber scenarios", description = "Runs Cucumber Scenarios", dataProvider = "scenarios")
public void testCucumberCcenario(PickleEventWrapper pickleEvent) throws Throwable {
PickleEvent event = pickleEvent.getPickleEvent();
mockActiveBucket();
testNGCucumberRunner.runScenario(pickleEvent.getPickleEvent());
Assert.assertTrue(true);
}
#DataProvider(name = "scenarios")
public Object[][] scenarios() {
Object[][] scenarios = testNGCucumberRunner.provideScenarios();
return new Object[][]{{scenarios[0][0]}};
}
#DataProvider(name = "users")
public Object[][] users() {
return new Object[][]{{"user1"}, {"user2"}};
}
}
class Util {
public static int getBucketId(long eventTimestamp){
Long minsPast5MinBoundary = (eventTimestamp % TimeUnit.MINUTES.toMillis(5))/TimeUnit.MINUTES.toMillis(1);
return minsPast5MinBoundary.intValue();
}
}
The above test fails to load BDD scenarios dataProvider if I enable PrepareForTest annotation on the test. However, the other test which uses dataProvider works fine in both cases(enable or disable PrepareForTest)
ERROR:
Data provider mismatch
Method: testCucumberCcenario([Parameter{index=0, type=io.cucumber.testng.PickleEventWrapper, declaredAnnotations=[]}])
Arguments: [(io.cucumber.testng.PickleEventWrapperImpl) "Sunday isn't Friday"]
at org.testng.internal.reflect.DataProviderMethodMatcher.getConformingArguments(DataProviderMethodMatcher.java:45)
at org.testng.internal.Parameters.injectParameters(Parameters.java:796)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:983)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
As a side effect of this, I am unable to mock static methods of util class while writing the BDD. I am new to cucumber BDD. Any help/pointers is appreciated.
After getting some help to root cause from #help-cucumber-jvm slack channel, I was able to root cause it to testng+powermock with dataproviders using custom classes.
For example this test fails
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.mockito.Matchers.any;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
#PrepareForTest(Util2.class)
public class TestngWithDataproviderTestngTest extends PowerMockTestCase {
#ObjectFactory
public org.testng.IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
private void mockActiveBucket() {
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.getBucketId(any(Long.class))).thenReturn(3);
}
#Test(dataProvider = "users")
public void testMockStatic(MyTestCaseImpl myTestCase) {
System.out.println("myTestCase: " + myTestCase);
System.out.println("static test passed");
mockActiveBucket();
Assert.assertTrue(true);
}
#DataProvider(name = "users")
public Object[][] users() {
return new Object[][]{{new MyTestCaseImpl(5)}};
}
}
//interface MyTestCase {
//}
class MyTestCaseImpl { //implements MyTestCase{
int i;
public MyTestCaseImpl() {
}
public MyTestCaseImpl(int i) {
this.i = i;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
class Util2 {
public static int getBucketId(long eventTimestamp) {
Long minsPast5MinBoundary = (eventTimestamp % TimeUnit.MINUTES.toMillis(5)) / TimeUnit.MINUTES.toMillis(1);
return minsPast5MinBoundary.intValue();
}
}
Here as mentioned, seems to be a known issue with a workaround. Hope this helps.

Error org.picocontainer.PicoCompositionException: Duplicate Keys not allowed. Duplicate

I was trying to achieve, Cucumber feature level parallel execution using pico Container.
When I am using a shared Driver in a context Class as below, I get org.picocontainer.PicoCompositionException: Duplicate Keys not allowed. Duplicate
public class Context{
private ThreadLocal<WebDriver> drivers = new ThreadLocal<>();
public void setDriver(WebDriver wd) {
drivers.set(wd);
}
public WebDriver getDriver() {
return drivers.get();
}
//Runner Class
import java.net.MalformedURLException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.CucumberFeatureWrapper;
import cucumber.api.testng.TestNGCucumberRunner;
import net.thumbtack.cucumber.picocontainer.example.step.SharedDriver;
import cucumber.api.testng.*;
#CucumberOptions (glue = {"net.thumbtack.cucumber.picocontainer.example.step"},
features = "src/main/resources/"
,tags = {"#Scenario2,#Scenario3"})
public class TestRunner {
public TestRunner() throws MalformedURLException {
super();
// TODO Auto-generated constructor stub
}
private TestNGCucumberRunner testNGCucumberRunner;
#BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
System.setProperty("ExecEnv","Docker");
}
// #Test(dataProvider = "features")
// public void feature(PickleEventWrapper eventwrapper,CucumberFeatureWrapper cucumberFeature) throws Throwable {
#Test(groups="cucumber", description="Runs CucumberFeature",dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature){
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
// testNGCucumberRunner.runScenario(eventwrapper.getPickleEvent());
}
#DataProvider(parallel=true)
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
// return testNGCucumberRunner.provideScenarios();
}
#AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
testNGCucumberRunner.finish();
}
}

Run appium test with Testng and logj4,Get err instantiating class org.apache.logging.log4j.spi.Provider

I'm trying to run an appium test on a real ios device using java, testng, and log4j. I am not too familiar with log4j. I am getting the following error in eclipse.
org.testng.TestNGException:
An error occurred while instantiating class MobileTests.AppiumIOSTestAppTest1: org.apache.logging.log4j.spi.Provider: Provider org.apache.logging.slf4j.SLF4JProvider not found
package MobileTests;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import org.apache.log4j.Logger;
import Base.TestBase;
import Common.ScreenshotURL;
import Locators.LocatorMethods;
public class AppiumIOSTestAppTest1 extends TestBase{
static SoftAssert softAssert = new SoftAssert();
static Logger log = Logger.getLogger(AppiumIOSTestAppTest1.class);
String className = this.getClass().getSimpleName();
Date date1= new Date();
String originaltimestamp = new Timestamp(date1.getTime()).toString();
String timestamp = originaltimestamp.replace(':', 'x').substring(11);
String foldername = folderpath+className+timestamp;
String error = "";
String errorname = "";
#Test
public void iosTestAppTest1 () throws IOException, InterruptedException
{
try
{
LocatorMethods.clickByXpath(driver, "textfield1.xpath");
LocatorMethods.sendKeysIntoElementByXpath(driver, "textfield1.xpath", Integer.toString(8));
LocatorMethods.clickByXpath(driver, "textfield2.xpath");
LocatorMethods.sendKeysIntoElementByXpath(driver, "textfield2.xpath", Integer.toString(9));
LocatorMethods.clickByXpath(driver, "compute.xpath");
String answer = LocatorMethods.getTextByXpath(driver, "answer.xpath");
try
{
Assert.assertTrue(answer.equalsIgnoreCase(Integer.toString(17)), "Answer is wrong.");
}
catch(AssertionError e)
{
log.debug("Wrong answer was calculated.");
log.error("This is an exception", e);
//error = e.toString();
//System.out.println(error);
errorname = "wronganswer";
ScreenshotURL.screenshotURL(driver, foldername, errorname, error);
softAssert.fail();
}
}
catch(AssertionError e)
{
System.out.println(e);
}
softAssert.assertAll();
}
#AfterMethod
public static void OnFailure(ITestResult testResult) throws IOException {
if (testResult.getStatus() == ITestResult.FAILURE)
{
System.out.println(testResult.getStatus());
}
}
}

CDI #Decorator, Is there a way to deactivate a decorator at runtime?

I use the following workaround in order to control the behaviour of a #Decorator since I couldn't find a way to deactivate it.
if (!FacesContext.getCurrentInstance().getViewRoot().getViewId()
.endsWith("decoratorDemo.xhtml")) {
return transInterBean.getTransactionalInsertRecords();
} else {
...
}
Is there no way to decide at runtime whether a decorator should be applied?
package com.cdi.decorators;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.enterprise.inject.Any;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import com.cdi.cdibeans.TransactionalInterceptor;
import com.cdi.cdibeans.TransactionalInterceptorBean;
#Decorator
public abstract class TransactionalInterceptorDecorator implements
TransactionalInterceptor {
/**
*
*/
private static final long serialVersionUID = -1191671082441891759L;
#Inject
#Delegate
#Any
TransactionalInterceptorBean transInterBean;
#Override
public ArrayList<String> getTransactionalInsertRecords()
throws SQLException {
ArrayList<String> records = new ArrayList<String>();
if (!FacesContext.getCurrentInstance().getViewRoot().getViewId()
.endsWith("decoratorDemo.xhtml")) {
return transInterBean.getTransactionalInsertRecords();
} else {
Iterator<String> iter = transInterBean
.getTransactionalInsertRecords().iterator();
while (iter.hasNext()) {
String record = iter.next();
records.add(record);
records.add(">>>Decorator<<< Added record ... ");
}
if (records.isEmpty()) {
records.add(">>>Decorator<<< Currently there are no records yet!");
}
return records;
}
}
}
Deltaspike has an exclude feature ... may be this could help, I didn't try it with decorators.

Resources