FakeItEasy mocked method won't return object, instead nullReferenceException - fakeiteasy

What I'm trying to do
I want a method, GetDirectoryInfo on a faked interface called fakeHiveReader to return a DirectoryInfo object.
I have to use the constructor to create the DirectoryInfo object I want to return, because that constructor calls a protected constructor for the parent class.
It's important that the method returns this specific DirectoryInfo object, so that I can check that later on, this object is used as a parameter for an important method.
The problem
The object is created fine, and I can see using breakpoints that the constructor is working, but then the last line throws an exception. If you run debug it stops on the line with a "NullReferenceException was unhandled by user code" pop-up. If you "View Detail" it says "System.NullReferenceException" and "Object reference not set to an instance of an object."
Any ideas would be hugely appreciated.
var fakeHiveReader = A.Fake<IHiveReader>();
DirectoryInfo di_1 = new DirectoryInfo(3, 4, "\\GeoWoods", "Gwood2", "Good", DateTimeOffset.UtcNow, true);
A.CallTo(() => fakeHiveReader.GetDirectoryInfo(#"\")).Returns(di_1);

Related

How to mock DbUpdateConcurrencyException

I'm trying to mock function in my service to throw a DbUpdateConcurrencyException. My code only needs to check for an exception of type DbUpdateConcurrencyException and doesn't need to read the exception message or list of entries that the constructor asks for.
I want to set up the Mock by calling a parameter-less constructor for DbUpdateConcurrencyException, but that doesn't exist in EFCore.
var mockService = new Mock<IMyService>();
mockService.Setup(service => service.UpdateFooAsync(It.IsNotNull<Data.Foo>())).Throws(new DbUpdateConcurrencyException());
I've tried calling new DbUpdateConcurrencyException() with some parameters, but there's some checks that happen on the parameters that prevents me from doing this with null/empty data.
new DbUpdateConcurrencyException(null, null) gives:
Message: System.ArgumentNullException : Value cannot be null.
Parameter name: entries
new DbUpdateConcurrencyException("", new List<IUpdateEntry>()) gives:
Message: System.ArgumentException : The collection argument 'entries' must contain at least one element.
Is there a way in Moq that I can mock the DbUpdateConcurrencyException without having to go through the checks that the constructor has?
Based on docs you have shared in comments you should use ctor with two parameters. The trick is to provide not null string and not empty List<IUpdateEntry>, moq could help you with that, e.g.
new DbUpdateConcurrencyException(string.Empty, new List<IUpdateEntry>{Mock.Of<IUpdateEntry>()});

Extbase Repository objectType = NULL

We are migrating a 4.5 Extension to 7.2. One special case is strange. Trying to get a findOneByUid brings a "No class name was given to retrieve the Data Map for." Error.
Accessing via another object and using the DebuggerUtility it allows us to navigate to the object that fails, and there we can see, the objectType is NULL.
Any clue where to search? All the other objects can be accessed via findOneByUid.
How would you proceed to find the issue?
Adding the following lines solved the problem... any idea how to avoid this?
public function __construct() {
$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$this->objectType = \TYPO3\CMS\Core\Utility\ClassNamingUtility::translateRepositoryNameToModelName($this->getRepositoryClassName());
}
The object type can only be null if the constructor of the repository has been overridden in a subclass without a call to the parent constructor. parent::__construct();
Instead of using the constructor, you should make use of the method initializeObject, which gets called after the constructor and which can safely be overridden.

WinJS.Class.define() - refer to member function in constructor

I have a WinJS class defined as follows and would like to use a member function in the constructor:
WinJS.Class.define(
function() {
setInterval(myMemberFunction, 100);
},
{ // Member variables
myMemberFunction: function() {
// Do something
}
});
Unfortunately it looks like I can't resolve member functions in that manner in the constructor. This code all lives in a module so I could move myMemberFunction up the hierarchy and access it from the constructor, however the drawback is that "this" would no longer refer to the instance of my WinJS class. What's the recommended method for accessing instance members in a WinJS from the constructor?
Generally speaking, you refer to any method or property using "this," as in this.myProperty. In the case of event handlers, you need to make sure that the "this" that you see inside the handler is the instance "this". That's the purpose of the bind method of a function object. So you do this:
setInterval(this.myMemberFunction.bind(this), 100);
This makes sure that you bind the right "this" instance to the callback. Because I've seen this question pop up frequently (use of .bind is all over the Windows SDK samples), I wrote about this in more detail on http://www.kraigbrockschmidt.com/2012/11/28/purpose-function-dot-bind/.
Just to note, this is pure JavaScript; nothing particular to WinJS or Windows Store apps.

PHPUnit mock a controller with reference parameter?

I have a class:
class Hello {
function doSomething(&$reference, $normalParameter) {
// do stuff...
}
}
Then I have a controller:
class myController {
function goNowAction() {
$hello = new Hello();
$var = new stdClass();
$var2 = new stdClass();
$bla = $hello->doSomething($var, $var2);
}
}
The "goNow" action I call using my tests like so:
$this->dispatch('/my/go-now');
I want to mock the "doSomething" method so it returns the word "GONOW!" as the result. How do I do that?
I've tried creating a mock
$mock = $this->getMock('Hello ', array('doSomething'));
And then adding the return:
$stub->expects($this->any())
->method('discoverRoute2')
->will($this->returnValue("GONOW!"));
But I'm stumped as to how to hook this up to the actual controller that I'm testing. What do I have to do to get it to actually call the mocked method?
You could create a mock for the reference, or if it is just a simple reference as your code shows, send a variable. Then the normal mock call may be called and tested.
$ReferenceVariable= 'empty';
$mock = $this->getMock('Hello ', array('doSomething'));
$stub->expects($this->any())
->method('discoverRoute2')
->will($this->returnValue("GONOW!"));
$this->assertEquals('GONOW!', $stub->doSomething($ReferenceVariable, 'TextParameter'));
Your example code does not explain your problem properly.
Your method allows two parameters, the first being passed as a reference. But you create two objects for the two parameters. Objects are ALWAYS passed as a reference, no matter what the declaration of the function says.
I would suggest not to declare a parameter to be passed as a reference unless there is a valid reason to do so. If you expect a parameter to be a certain object, add a typehint. If it must not be an object, try to avoid passing it as a reference variable (this will lead to confusing anyways, especially if you explicitly pass an object as a reference because everybody will try to figure out why you did it).
But your real question is this:
But I'm stumped as to how to hook this up to the actual controller that I'm testing. What do I have to do to get it to actually call the mocked method?
And the answer is: Don't create the object directly in the controller with new Hello. You have to pass the object that should get used into that controller. And this object is either the real thing, or the mock object in the test.
The way to achieve this is called "dependency injection" or "inversion of control". Explanaitions of what this means should be found with any search engine.
In short: Pass the object to be used into another object instead of creating it inside. You could use the constructor to accept the object as a parameter, or the method could allow for one additional parameter itself. You could also write a setter function that (optionally) gets called and replaces the usual default object with the new instance.

content inserted into ghashtable being destroyed

I have a ghashtable object as member of my class. I have created new object of it at constructor. I am calling this function iteratively. When i checked the size of hashtable at each method call it's giving as 0, even if i eep on adding new key-value pairs.
void myFunction(string inString)
{
string val = "some value";
printf("Size:%d",g_hash_table_size(mTable));
g_hash_table_insert(mTable,(void*)inString.c_str(),(void*)val.c_str());
printf("Size:%d",g_hash_table_size(mTable));
}
What could be the reason behind this problem.
The C++ strings are going out of scope and getting destroyed, leaving the hash table with dangling pointers to invalid memory. I don't know if know if that's the only problem in your program but it's a problem visible from looking at the part you posted.