How to Mole SPFieldUser from SPField - unit-testing

Im writing the unit test case using Moles for my SharePoint application
I'm stuck up at the below lines of code I'm unable to type cast SPField to SPFieldUser.
SField subfield = list.Fields.GetField("Subscriber");
SPFieldUser userfield = (SPFieldUser)subfield;
userfield.SelectionGroup = web.Groups["Focal Points"].ID; //error line shown in pex
I'm getting "NullReference" exception at the above line
Can someone guide me here..

Although I am sure you have already checked these...:
Does GetField("Subscriber") return an object?
Does userfield get set to an object?
Is userfield.SelectionGroup null?
Try this syntax:
SPFieldUser userfield = subfield as SPFieldUser;
So, these all fail. Let's examine covariance of SPFieldUser to SField. The inheritance hierarchy is:
System.Object
Microsoft.SharePoint.SPField
Microsoft.SharePoint.SPFieldLookup
Microsoft.SharePoint.SPFieldUser
Unfortunately, I do not have the Microsoft.SharePoint library, to see if the SPFieldLookup classis hiding something important in SPField.

Related

Zend framework 3 form issue with binding entities that use return type hinting

As I'm upgrading my application to PHP 7.3, I decided to add return type hinting to my entities methods.
An example would be something like this:
class User {
private $username;
public method getUsername(): string { return $this->username}
}
I use this entity in a form (to create users) where I bind it like so:
$user = new User();
$form->bind($user);
$form->setData($data);
However I get this error which is caused by the hydrator (I'm using the DoctrineObject hydrator)
Return value of Admin\Entity\Auth\User::getUsername() must be of the type string, null returned
#0 ...\vendor\doctrine\doctrine-module\src\DoctrineModule\Stdlib\Hydrator\DoctrineObject.php(220): Admin\Entity\Auth\User->getUsername()
#1 ...\vendor\doctrine\doctrine-module\src\DoctrineModule\Stdlib\Hydrator\DoctrineObject.php(116): DoctrineModule\Stdlib\Hydrator\DoctrineObject->extractByValue(Object(Admin\Entity\Auth\User))
#2 ...\vendor\zendframework\zend-form\src\Fieldset.php(650): DoctrineModule\Stdlib\Hydrator\DoctrineObject->extract(Object(Admin\Entity\Auth\User))
...
From the snippet above it's obvious that it's calling the getUsername method on an "empty" object, which makes it return null and throw the exception.
This is not logically correct as the entity is supposed to have a username so marking it as nullable (?string) is not correct.
Is there any better solution to this? Because making every single method return type nullable seems like a hack that defeats the purpose.

How can I cast/convert an anonymous type from HttpResponseMessage for unit testing?

I have been tasked with writing a unit test for the following Web API 2 action:
public HttpResponseMessage Get()
{
IEnumerable<KeyValuePair<long, string>> things = _service.GetSomething();
return ActionContext.Request.CreateResponse(things.Select(x => new
{
Thing1 = x.Prop1.ToString(),
Thing2 = x.Prop2
}).ToArray());
}
I am testing the status code and that works fine, but I have not been able to figure out how I can extract the content data and test it. Here's my test so far:
[TestMethod]
public void GetReturnsOkAndExpectedType()
{
var controller = GetTheController();
var response = controller.Get();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
dynamic responseContent;
Assert.IsTrue(response.TryGetContentValue(out responseContent));
//???? How can I cast/convert responseContent here ????
}
If I debug the test and inspect responseContent in the immediate window, I see this (I have mocked/stubbed in a single fake value for testing):
{<>f__AnonymousType1<string, string>[1]}
[0]: { Thing1 = "123", Thing2 = "unit test" }
I can cast this as an array of object, but if I try and extract the values by their property names, I get an error (immediate window again):
((object[])responseContent)[0].Thing1
'object' does not contain a definition for 'Thing1' and no extension method 'Thing1' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Similarly, if I try to cast and project to an anonymous type of the same shape, it will not compile:
//Thing1 and Thing2 get red-lined here as 'cannot resolve symbol'
var castResult = ((object[]) responseContent).ToList().Select(x => new {x.Thing1, x.Thing2});
I know I can probably achieve what I want to do if I serialize/deserialize everything using something like JsonConvert, but that doesn't seem like the "right" way to do it. I feel like I'm missing something fundamental, here. How can I cast/convert an anonymous type from HttpResponseMessage for unit testing?
As has been said by #Daniel J.G. in the comments above, one option would be to use reflection to fetch the values of your properties. Since you appear to be using MS testing framework another alternative is to use the PrivateObject class to do some of the reflection work for you.
So, you could do something like this in your test:
var poContent = ((object[])responseContent).Select(x => new PrivateObject(x)).ToArray();
Assert.AreEqual("123", poContent[0].GetProperty("Thing1"));
Assert.AreEqual("unit test", poContent[0].GetProperty("Thing2"));

Issue with $softDelete in model testing

I am using laravel-test-helper package by jeffrey way in laravel 4 to test my models. When I use
protected $softDelete = true;
in my model, the following assertion fails:
public function testMyModel()
{
$obj = Factory::create('Modelname');
Assert::equals(1,$obj->count());
}
and when I run the test without the $softDelete variable, it works fine.
Any clue to whats wrong?
This is the stack trace of the phpunit command, if it is of any help:
/var/www/project/vendor/way/laravel-test-helpers/src/Way/Tests/TestFacade.php:41
/var/www/project/vendor/way/laravel-test-helpers/src/Way/Tests/TestFacade.php:25
/var/www/project/vendor/way/laravel-test-helpers/src/Way/Tests/TestFacade.php:55
/var/www/project/app/tests/models/ModelTest.php:13
/var/www/project/app/tests/models/ModelTest.php:13
The Factory::create() will create random variables for your models. Because your are using 'softDelete' - there is a field in your table called 'deleted_at'. So the factory is putting data in there, and Laravel thinks the record is deleted, so ->count() returns 0.
You need to explicitly set Factory default for the deleted_at to null like this:
$obj = Factory::create('Modelname', array('deleted_at' => null));

Missing descriptor exception while using Eclipselink Expressionbuilder

I have an entity Person with fields String name and String designation. When I tried to query using Eclipselink ExpressionBuilder, as:
Project project=new Project();
Login login=new DatabaseLogin();
login.setUserName("root");
login.setPassword("root");
project.setLogin(login);
DatabaseSession session=project.createDatabaseSession();
ExpressionBuilder expBuilder=new ExpressionBuilder();
Expression expression=expBuilder.get("name").equalsIgnoreCase("SomeName");
Vector readAllObjects = session.readAllObjects(Person.class, expression);
On executing last statement the following exception is thrown :
Exception [EclipseLink-6007] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.QueryException
Exception Description: Missing descriptor for [class com.mycompany.entity.Person].
Query: ReadAllQuery(referenceClass=Person)
What might be the reason? Thanks in advance...
At last I got it. Instead of DatabaseSession, org.eclipse.persistence.sessions.server.ClientSession had to be used.
JpaEntityManager jpaEntityManager=em.unwrap(JpaEntityManager.class);
ClientSession session=jpaEntityManager.getServerSession().acquireClientSession();
ExpressionBuilder expBuilder=new ExpressionBuilder();
Expression expression=expBuilder.get("name").equalsIgnoreCase("SomeName");
Vector readAllObjects = session.readAllObjects(Person.class, expression);
em is the EntityManager.
This solved the issue.
You did not add a descriptor for Person. You need to map it to be able to query it.
Also consider using JPA.

Null Reference Excepion when saving data on subsonic 3

I am testing subsonic 3, i can query my database but when i am inserting a record i have an exception. Here is my code:
Client lClient = new Client();
lClient.Name = "Peter";
lClient.FullName = "Richards";
lCliente.Save();
And i have a null reference exception on this generated code:
var newKey=_repo.Add(this,provider);
Any help is appreciated.
I am using ActiveRecords
I had a similar problem, with code not unlike the following:
var pending = myTable.SingleOrDefault(x => x.Id == 1);
if (pending == null)
pending = new myTable();
pending.Id = 1;
pending.MyDate = DateTime.Now;
pending.MyString = someString;
pending.Save();
This worked the first time I ran it, on an empty table, but not the second time when updating. I got a nullreference exception somewhere inside the subsonic repository. The solution was to add a primary key, as Rob suggested.
Just thought I'd mention it (thanks Rob).
Where does the null reference exception actually happen? Is _repo null?
Try and double check that you don’t have any columns in the “Client” table which are not nullable and you don’t set any value.
Also make sure you PK is handled correctly (check you have the [Property.IsForeignKey=true;] attribute)
Do you have NullReferenceException Checked in (file menu) Debug -> Exceptions (press Find and type NullReferenceException, press OK)?
I downloaded the SubSonic code and used it as reference for my project, the exception is thrown in SubSonic.Core\Repository\SubSonicRepository.cs:209 because prop is not checked for null at line 208, and any exceptions are swallowed as evidenced by line 213.
What happens is visual studio breaks on all the exceptions checked in the mentioned dialog. So in one way, this is the expected behaviour from the code.
What actually causes prop to become null, in my case, the table field name is lower-case, but the property is actually cased properly.
From Immediate:
tbl.PrimaryKey.Name
"playerinformationid"
item.GetType().GetProperties()
{System.Reflection.PropertyInfo[11]}
[0]: {System.Collections.Generic.IList`1[SubSonic.Schema.IColumn] Columns}
// *snip*
[5]: {Int32 PlayerInformationid}
// *snip*
item.GetType().GetProperty("PlayerInformationid")
{Int32 PlayerInformationid} // Works!
item.GetType().GetProperty(tbl.PrimaryKey.Name)
null
I hacked this together to "just make it work" (Warning: newbie at 3.5 stuff)
-var prop = item.GetType().GetProperty(tbl.PrimaryKey.Name);
+var lowerCasedPrimaryKeyName = tbl.PrimaryKey.Name.ToLowerInvariant();
+var prop = item.GetType().GetProperties().First<System.Reflection.PropertyInfo>(x => x.Name.ToLowerInvariant() == lowerCasedPrimaryKeyName);
Does your table have a PrimaryKey? It doesn't sound like it does. If not - this is your problem.