Phpunit Test -Can't find entity (Symfony) - symfony

I am new to symfony and phpunit testing and have been getting this error
Cannot stub or mock class or interface "com\twcl\agripayrollBundle\Entity\Payrollperiod" which does not exist
This is my test which is in the Selenium Test files in the Tests directory.
use com\twcl\agripayrollBundle\Mapping\PayPeriodManager;
use com\twcl\agripayrollBundle\Entity\Payrollperiod;
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Persistence\ObjectManager;
class PayrollperiodManagerTest extends PHPUnit_Framework_TestCase {public function testPayrollPeriodManager()
{
$payperiod= $this->createMock(Payrollperiod::class);
$payperiod->expects($this->once())
->method('setstartDate')
->will($this->setValue(2011-01-01));
$payperiod->expects($this->once())
->method('setendDate')
->will($this->setValue(2011-01-18));
$payperiod->expects($this->once())
->method('setState')
->will($this->setValue('Active'));
var_dump($payperiod);
die();
}
}
This is my phpunit.xml.dist
<!-- http://phpunit.de/manual/4.1/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="bootstrap.php.cache"
>
<testsuites>
<testsuite name="Project Test Suite">
<directory>../src/*/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/Tests</directory>
</testsuite>
</testsuites>
<!--
<php>
<server name="KERNEL_DIR" value="/path/to/your/app/" />
</php>
-->
<filter>
<whitelist>
<directory>../src</directory>
<exclude>
<directory>../src/*/*Bundle/Resources</directory>
<directory>../src/*/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/Resources</directory>
<directory>../src/*/Bundle/*Bundle/Tests</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
My autoloader
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;
/**
* #var ClassLoader $loader
*/
$loader = require __DIR__.'/../vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;

Related

Symfony 5 unittest can't fetch entity collection

my collection is empty while I try to access it in a unittest. In dev && prod env it is accessable as aspected.
One customerOrder can have multiple invoices and one invoice can have one customerOrder.
class CustomerOrderServiceTest extends KernelTestCase
{
use RefreshDatabaseTrait;
public function testAdd()
{
self::bootKernel();
$container = self::$container;
$orderRepository = $container->get(CustomerOrderRepository::class);
$customerOrder = $orderRepository->find(1);
foreach ($customerOrder->getInvoices() as $invoice) {
dump('Invoice id: ' . $invoice->getId());
}
dump('Invoice count: ' . $customerOrder->getInvoices()->count());
$invoiceRepository = $container->get(InvoiceRepository::class);
$invoice = $invoiceRepository->find(1);
dump('Order id: ' . $invoice->getCustomerOrder()->getId());
dump('Invoice count: ' . $invoice->getCustomerOrder()->getInvoices()->count());
}
}
The Output is
Testing Project Test Suite
^ "Invoice count: 0"
^ "Order id: 1"
^ "Invoice count: 0"
So the Order is accessable over the invoice but not the other way around.
The entities:
/**
* CustomerOrder
* #ORM\Entity(repositoryClass="App\Repository\CustomerOrderRepository")
*/
class CustomerOrder{
/**
* #var Collection
* #ORM\OneToMany(targetEntity="App\Entity\Invoice", mappedBy="customerOrder", cascade={"persist"}, fetch="EAGER")
*/
private $invoices;
}
/**
* Invoice
* #ORM\Entity(repositoryClass="App\Repository\InvoiceRepository")
* #ORM\Table(uniqueConstraints={#ORM\UniqueConstraint(name="number",columns={"number", "owner"})})
*/
class Invoice{
/**
* #var CustomerOrder
*/
private $customerOrder;
}
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="bin/.phpunit/phpunit.xsd"
colors="true"
bootstrap="tests/bootstrap.php"
>
<php>
<ini name="error_reporting" value="-1"/>
<server name="APP_ENV" value="test" force="true"/>
<server name="SHELL_VERBOSITY" value="-1"/>
<server name="SYMFONY_PHPUNIT_REMOVE" value=""/>
<server name="SYMFONY_PHPUNIT_VERSION" value="7.5"/>
<!-- ###+ symfony/framework-bundle ### -->
<env name="APP_ENV" value="test" force="true"/>
<env name="APP_SECRET" value="*****"/>
<!-- ###- symfony/framework-bundle ### -->
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
<listeners>
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener" />
</listeners>
</phpunit>

No mapping found for HTTP request with URI [/demoApp/add] in DispatcherServlet with name 'newApp'

No mapping found for HTTP request with URI [/demoApp/index.jsp] in DispatcherServlet with name 'newApp'
I am getting this error please help.I am using Tomcat v9.0 server.
index.jsp
<html>
<body>
<form action="add">
<input type="text" name="t1"><br>
<input type="text" name="t2"><br>
<input type="submit"><br>
</form>
</body>
</html>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>newApp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>newApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
newApp-servlet.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:ctx="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd ">
<mvc:annotation-driven />
<ctx:annotation-config></ctx:annotation-config>
<ctx:component-scan base-package="com.newApp"></ctx:component-scan>
</beans>
AddController.java
package com.newApp;
import java.lang.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class AddController {
#RequestMapping("/add")
public void add()
{
System.out.println("I am good");
}
}
program should print "I am good" on the console but it is showing error on browser "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."
on the console it is showing "No mapping found for HTTP request with URI [/demoApp/add] in DispatcherServlet with name 'newApp'".
This error accures when i click on submit button on jsp page.
If you want to use view technology like jsp.
You could add bean definition of InternalResourceViewResolver class into your spring configuration file
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
see official docs
I got the same issue and resolved it.
Please add missing folder src/main/java [add package name (for example: com.dev) while adding a class] and then add the java class in that instead of src/main/resource folder. This is the culprit. Let me know for any issue at parixitk28#gmail.com.

request mapping is not taking me to the desired page, its showing error 404

I am a spring beginner, I used controller and request mapping to go to
some java file from index.jsp but its showing 404 Error. I am putting
right urlmapping and requestmapping and controllers as I saw in a spring
tutorial.
I have tried including more dependencies, changing the code as I saw
someplace else, but nothing working. Please help me with this code.
Thanks in Advance
index.jsp:
<html>
<body>
<form action="add">
<input type="text" name="t1"><br>
<input type="text" name="t2"><br>
<input type="submit">
</form>
</body>
</html>
web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>bhoomika</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bhoomika</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
bhoomika-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="garg.bhoomika"></context:component-
scan>
</beans>
AddController.java
package garg.bhoomika;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class AddController
{
#RequestMapping("/add")
public void add()
{
System.out.println("I am here");
}
}
Error:
org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVC/add] in DispatcherServlet with name 'bhoomika'
For now you should use <mvc:annotation-driven/> in your spring confuguration file to enable MVC configuration as described in official doc
Try to replace entry <context:annotation-config> to <mvc:annotation-driven/>.
And if you want to go to your index.jsp you should change method add() so that it returned view name as a String:
#RequestMapping("/add")
public String add() {
return "index";
}
Also you can see the exhaustive and descriptive answer to similar question this. It'll be useful.

EasyAdminBundle entities labels translations

I'm unable to configure translations. My config.yml has (among others) this entry:
easy_admin:
entities:
Blog:
label: app.blog
class: AppBundle\Entity\Blog
I've also created a translation resorce: messages.es.xliff with this entry:
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file source-language="es" target-language="es" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="app.blog">
<source>app.blog</source>
<target>Blog</target>
</trans-unit>
</body>
</file>
</xliff>
but the translated literal doesn't appear in the left menu.
Thank you very much for your help.
At last I've changed the name of translation ressource to EasyAdminBundle.es.yml and now everything works fine.
Ensure you have the translator service enabled. In app/config/config.yml:
framework:
translator: { fallbacks: ["en"] }

Spring MVC - form generating new model object instances

I have a simple mvc application, which lists all rules in a DB, and allows a user to select a specific row to delete that rule. The controller has a simple listRules() method which adds two model objects to the ModelMap.
#Controller
public class RulesController {
#Resource
private RuleManager ruleManager;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView listRules() {
ModelAndView mv = new ModelAndView("/rules");
List<Rule> rules = this.ruleManager.getAllRules();
ListRulesModel listRulesModel = new ListRulesModel();
listRulesModel.setRules(rules);
mv.addObject("listRulesModel",listRulesModel);
SelectedRuleModel selectedRuleModel = new SelectedRuleModel();
mv.addObject("selectedRuleModel",selectedRuleModel);
return mv;
}
#RequestMapping(value = "/submit", method = RequestMethod.POST, params = {"delete"})
public ModelAndView deleteRule(#ModelAttribute("selectedRuleModel") SelectedRuleModel selectedRuleModel,ModelMap model) {
System.out.println("deleteRule "+selectedRuleModel.hashCode());
System.out.println("model "+model);
if(selectedRuleModel.getRuleId()!=null)
getRuleManager().deleteRule(getRuleManager().getRule(selectedRuleModel.getRuleId()));
return new ModelAndView("redirect:/");
}
My model objects are
public class ListRulesModel {
private List<Rule> rules = null;
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
}
and
public class SelectedRuleModel {
#NotNull
private Integer ruleId = null;
public Integer getRuleId() {
return ruleId;
}
public void setRuleId(Integer ruleId) {
this.ruleId = ruleId;
}
#Override
public String toString() {
return String.format("SelectedRuleModel [ruleId=%s]", ruleId);
}
}
The main elements of my view are a table form which shows each rule as a row. A radiobutton should populate the 'selectedRuleModel.ruleId' field with the value of the rule within the list.
<head>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-2.1.1.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.tablesorter.min.js"/>"> </script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.tablesorter.widgets.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/rules.js"/>"></script>
<link href="<c:url value="/resources/css/base.css"/>" rel="stylesheet"/>
<link href="<c:url value="/resources/css/theme.blue.css"/>" rel="stylesheet"/>
<link href="<c:url value="/resources/css/rules.css"/>" rel="stylesheet"/>
</head>
<form:form method="POST" action="submit" modelAttribute="selectedRuleModel">
<button type="submit" name="delete" value="delete" class="btn btn-primary">Delete Selected Rule</button>
...
<c:forEach items="${listRulesModel.rules}" var="rule" varStatus="status">
<tr>
<td><form:radiobutton path="ruleId" value="${rule.id}"/></td>
<td>${rule.name}</td>
<td>${rule.batch}</td>
...
</form>
Everytime i submit the "delete row" form it appears that a new 'SelectedRuleModel' object is passed as a parameter to the deleteRule() method, such that the 'ruleId' value is always null. What am io doing wrong with my model/method mapping?
The generated HTML is
<form id="selectedRuleModel" action="submit" method="POST">
<button type="submit" name="amend" value="amend" class="btn btn-primary">Amend Selected Rule</button>
<button type="submit" name="branch" value="branch" class="btn btn-primary">Branch Selected Rule</button>
<button type="submit" name="delete" value="delete" class="btn btn-primary">Delete Selected Rule</button>
</div>
<!-- Add rule table -->
<table id="rulesTable" class="tablesorter">
<thead>
<tr>
<th>ID</th>
<th>Rule Name</th>
....
</tr>
</thead>
<tbody>
<tr>
<td><input id="ruleId2" name="ruleId" type="radio" value="20"/></td>
<td>Gender_Balance</td>
<td>*</td>
....
EDIT - I've update the controller method deleteRule() to include the BindResult object.
#RequestMapping(value = "/submit", method = RequestMethod.POST, params = {"delete"})
public ModelAndView deleteRule(
#Valid #ModelAttribute("selectedRuleModel") SelectedRuleModel selectedRuleModel,
BindingResult result, ModelMap model) {
System.out.println("deleteRule "+selectedRuleModel.getRuleId());
System.out.println("model "+model.toString());
System.out.println("BindingResult "+result.toString());
if(selectedRuleModel.getRuleId()!=null)
getRuleManager().deleteRule(getRuleManager().getRule(selectedRuleModel.getRuleId()));
return new ModelAndView("redirect:/");
}
As you can see in the logging for this method, the 'selectedRuleModel' is null but the model has a 'selectedRuleModel' with a null 'ruleId' value.
2014-10-14 11:18:21,428 INFO [STDOUT] (http-127.0.0.1-8080-2) deleteRule null
2014-10-14 11:18:21,428 INFO [STDOUT] (http-127.0.0.1-8080-2) model {selectedRuleModel=SelectedRuleModel [ruleId=null], org.springframework.validation.BindingResult.selectedRuleModel=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
2014-10-14 11:18:21,428 INFO [STDOUT] (http-127.0.0.1-8080-2) BindingResult org.springframework.validation.BeanPropertyBindingResult: 0 errors
EDIT Adding web.xml and applicationContext.xml in case someone spots that i'm not initialising some required component correctly.
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>hedgingcorrection</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>namespace</param-name>
<param-value>applicationContext</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hedgingcorrection</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<jsp-config>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
And my applicationContext.xml has
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:view-controller path="/"/>
<context:component-scan base-package="abc.xwz.web.correction.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
I removed the three mvc elements from my applicationContext.xml file it the form started working.
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:view-controller path="/"/>
FRIDAY EDIT - I've isolated the issue to the inclusion of the javascript elements in the jsp form. Without the javascript files included, the form submits data to the controller. When the scripts are added it seems that the form data is not correctly bound to the ModelAttribute object. The javascript files are primarily aimed at enabling the tablesorting features on the html table, so i can't understand why they are effecting the action of the submit buttons. 50 points for someone who can explain it.
The only thing I can think of is that rules.js or one of the other javascript imports may be disabling the radio button just before the submit - in which case no value would be submitted in the POST operation, which would then makes sense as to why the ModelAttribute is not being popualated.

Resources