Assigning to a stub class method in Moles while using partial stubs - moles

I've seen this question regarding partial stubs, but it does not quite tell me what I need to know.
I understand that, if I am using a Moles stub for a class (let's say, for DataService, I'm using SDataService), I can set the CallBase property to true so that, if there is no delegate for a particular method, the base implementation's method will be called. Great, but how do I assign a delegate to a particular method in this case?
If there is no way to do that, say I have an interface IDataService that I stub using SIDataService. I can easily assign a delegate to a method here. But, how do I tell it to call the corresponding method on DataService (an implementation of IDataService) if there is no delegate for a given method?
Thank you!
Edit:
I see now that the method needs to be virtual to be overridden in the first scenario above. I don't think that makes a whole lot of sense, but it is what it is.
So, focusing on the second scenario, would I have to create a Behavior? (And why isn't there one already for stubs like there is for moles?) Or is there a simpler way?

Delegates (detours) are set to stubs types the same way as mole types. For example, SIDataService.GetMemberProfile() is configured to return a mock object like this:
var memberMock = new Member() { Firstname="Joe", LastName="Schmoe" };
var stub = new SIDataService();
stub.GetMemberProfileMember = i => memberMock;

Related

How to make a function can be called only by specific class in swift?

I have two frameworks A and B. I have a public function inside B called getMap() which returns a copy of a map(which is a private variable in B). So I call getMap() in A to get this value. This is fine because it's a copy so whatever I do to the returned value it doesn't affect the actual variable inside B.
Now I did some processing to this value, I need to pass it back to B. Here is the problem: In order to pass it back, it has to be a public function, but I don't want other frameworks or application to call this function because only A should be making changes to this map value.
Is there any way to specify in B that only if A is calling the function then the value should be set, otherwise ignoring anyone else who is using this function? I've heard you can use delegate/protocol to achieve this but I don't understand.
Yes you should be able to achieve this using delegate/protocols. The protocol will still have to be public which means any class could implement the protocol but the simple solution to this would be to just not implement it any other class.
You would create the the protocol in framework B like this:
protocol FrameworkBDelegate {
func sendMapChanges(map: Map)
}
Then call the delegate method when you're ready send it back to the other framework:
func changeMap() {
var map = frameworkA.getMap()
// Do stuff to map...
delegate.sendMapChanges(map: map)
}
I don't want to write a whole tutorial on how implement delegation so here's a good one from Swift by Sundell: here
Let me know if you need any help.
This is not possible out of the box.
If you create a Framework than you have to decide if a method/class needs to be public or not. If a method is public than there isn't an out of the box solution which delivers a bullet proof solution which solves your requirement. In the end the method is public to ALL consumers of Framework B.
So, you will end up implementing some kind of access control mechanisms within Framework B. This means that Framework A needs to authenticate itself in some way (access code etc.).
The delegate pattern will not solve your issue as well, hence it also has to be public, so that Framework A can use it. However, if it's public than all consumers of Framework B can use it.

Any way to trigger creation of a list of all classes in a hierarchy in Swift 4?

Edit: So far it looks like the answer to my question is, "You can't do that in Swift." I currently have a solution whereby the subclass names are listed in an array and I loop around and instantiate them to trigger the process I'm describing below. If this is the best that can be done, I'll switch it to a plist so that least it's externally defined. Another option would be to scan a directory and load all files found, then I would just need to make sure the compiler output for certain classes is put into that directory...
I'm looking for a way to do something that I've done in C++ a few times. Essentially, I want to build a series of concrete classes that implement a particular protocol, and I want to those classes to automatically register themselves such that I can obtain a list of all such classes. It's a classic Prototype pattern (see GoF book) with a twist.
Here's my approach in C++; perhaps you can give me some ideas for how to do this in Swift 4? (This code is grossly simplified, but it should demonstrate the technique.)
class Base {
private:
static set<Base*> allClasses;
Base(Base &); // never defined
protected:
Base() {
allClasses.put(this);
}
public:
static set<Base*> getAllClasses();
virtual Base* clone() = 0;
};
As you can see, every time a subclass is instantiated, a pointer to the object will be added to the static Base::allClasses by the base class constructor.
This means every class inherited from Base can follow a simple pattern and it will be registered in Base::allClasses. My application can then retrieve the list of registered objects and manipulate them as required (clone new ones, call getter/setter methods, etc).
class Derived: public Base {
private:
static Derived global; // force default constructor call
Derived() {
// initialize the properties...
}
Derived(Derived &d) {
// whatever is needed for cloning...
}
public:
virtual Derived* clone() {
return new Derived(this);
}
};
My main application can retrieve the list of objects and use it to create new objects of classes that it knows nothing about. The base class could have a getName() method that the application uses to populate a menu; now the menu automatically updates when new subclasses are created with no code changes anywhere else in the application. This is a very powerful pattern in terms of producing extensible, loosely coupled code...
I want to do something similar in Swift. However, it looks like Swift is similar to Java, in that it has some kind of runtime loader and the subclasses in this scheme (such as Derived) are not loaded because they're never referenced. And if they're not loaded, then the global variable never triggers the constructor call and the object isn't registered with the base class. Breakpoints in the subclass constructor shows that it's not being invoked.
Is there a way to do the above? My goal is to be able to add a new subclass and have the application automatically pick up the fact that the class exists without me having to edit a plist file or doing anything other than writing the code and building the app.
Thanks for reading this far — I'm sure this is a bit of a tricky question to comprehend (I've had difficulty in the past explaining it!).
I'm answering my own question; maybe it'll help someone else.
My goal is to auto initialize subclasses such that they can register with a central authority and allow the application to retrieve a list of all such classes. As I put in my edited question, above, there doesn't appear to be a way to do this in Swift. I have confirmed this now.
I've tried a bunch of different techniques and nothing seems to work. My goal was to be able to add a .swift file with a class in it and rebuild, and have everything automagically know about the new class. I will be doing this a little differently, though.
I now plan to put all subclasses that need to be initialized this way into a particular directory in my application bundle, then my AppDelegate (or similar class) will be responsible for invoking a method that scans the directory using the filenames as the class names, and instantiating each one, thus building the list of "registered" subclasses.
When I have this working, I'll come back and post the code here (or in a GitHub project and link to it).
Same boat. So far the solution I've found is to list classes manually, but not as an array of strings (which is error-prone). An a array of classes such as this does the job:
class AClass {
class var subclasses: [AClass.Type] {
return [BClass.self, CClass.self, DClass.self]
}
}
As a bonus, this approach allows me to handle trees of classes, simply by overriding subclasses in each subclass.

How can I fake a Class used insite SUT using FakeItEasy

Am having a little trouble understanding what and what cannot be done using FakeItEasy. Suppose I have a class
public class ToBeTested{
public bool MethodToBeTested(){
SomeDependentClass dependentClass = new SomeDependentClass();
var result = dependentClass.DoSomething();
if(result) return "Something was true";
return "Something was false";
}
}
And I do something like below to fake the dependent class
var fakedDepClass = A.Fake<DependentClass>();
A.CallTo(fakedDepClass).WithReturnType<bool>().Returns(true);
How can i use this fakedDepClass when am testing MethodToBeTested. If DependentClass was passed as argument, then I can pass my fakedDepClass, but in my case it is not (also this is legacy code that I dont control).
Any ideas?
Thanks
K
Calling new SomeDependentClass() inside MethodToBeTested means that you get a concrete actual SomeDependentClass instance. It's not a fake, and cannot be a FakeItEasy fake.
You have to be able to inject the fake class into the code to be tested, either (as you say) via an argument to MethodToBeTested or perhaps through one of ToBeTested's constructors or properties.
If you can't do that, FakeItEasy will not be able to help you.
If you do not have the ability to change ToBeTested (and I'd ask why you're writing tests for it, but that's an aside), you may need to go with another isolation framework. I have used TypeMock Isolator for just the sort of situation you describe, and it did a good job.

How to call constructor with interface arguments when mocking a concrete class with Moq

I have the following class, which uses constructor injection:
public class Service : IService
{
public Service(IRepository repository, IProvider provider) { ... }
}
For most methods in this class, I simply create Moq mocks for IRepository and IProvider and construct the Service. However, there is one method in the class that calls several other methods in the same class. For testing this method, instead of testing all those methods together, I want to test that the method calls those methods correctly and processes their return values correctly.
The best way to do this is to mock Service. I've mocked concrete classes with Moq before without issue. I've even mocked concrete classes that require constructor arguments with Moq without issue. However, this is the first time I've needed to pass mocked arguments into the constructor for a mocked object. Naturally, I tried to do it this way:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
However, that does not work. Instead, I get the following error:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: My.Namespace.Service.
Could not find a constructor that would match given arguments:
Castle.Proxies.IRepository
Castle.Proxies.IProvider
This works fine if Service's constructor takes simple arguments like ints and strings, but not if it takes interfaces that I'm mocking. How do you do this?
Why are you mocking the service you are testing? If you are wishing to test the implementation of the Service class (whether that be calls to mocked objects or not), all you need are mocks for the two interfaces, not the test class.
Instead of:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
Shouldn't it be this instead?
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Service(repository.Object, provider.Object);
I realize that it is possible to mock concrete objects in some frameworks, but what is your intended purpose? The idea behind mocking something is to remove the actual implementation so that it does not influence your test. But in your question, you have stated that you wish to know that certain classes are called on properly, and then you wish to validate the results of those actions. That is undoubtedly testing the implementation, and for that reason, I am having a hard time seeing the goals of mocking the concrete object.
I had a very similar problem when my equivalent of Service had an internal constructor, so it was not visible to Moq.
I added
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
to my AssemblyInfo.cs file for the implementing project. Not sure if it is relevant, but I wanted to add a suggestion on the off chance that it helps you or someone else.
It must be old version issue, all is ok with latest version. Nick, Please check!
P.s.: I started bounty by misstake (I had wrong signature in my constructor).

Dont understand the concept of extends in URL.openConnection() in JAVA

Hi I am trying to learn JAVA deeply and so I am digging into the JDK source code in the following lines:
URL url = new URL("http://www.google.com");
URLConnection tmpConn = url.openConnection();
I attached the source code and set the breakpoint at the second line and stepped into the code. I can see the code flow is: URL.openConnection() -> sun.net.www.protocol.http.Handler.openConnection()
I have two questions about this
First In URL.openConnection() the code is:
public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}
handler is an object of URLStreamHandler, define as blow
transient URLStreamHandler handler;
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right? But there are a lot classes who implement this methods in sun.net.www.protocol (like http.Hanlder, ftp.Handler ) How should the code know which "openConnection" method it should call? In this example, this handler.openConnection() will go into http.Handler and it is correct. (if I set the url as ftp://www.google.com, it will go into ftp.Handler) I cannot understand the mechanism.
second. I have attached the source code so I can step into the JDK and see the variables but for many classes like sun.net.www.protocol.http.Handler, there are not source code in src.zip. I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip? Where can I find a comprehensive version of source code?
Thanks!
First the easy part:
... I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip?
Two reasons:
In the old days when the Java code base was proprietary, this was treated as secret-ish ... and not included in the src.zip. When they relicensed Java 6 under the GPL, they didn't bother to change this. (Don't know why. Ask Oracle.)
Because any code in the sun.* tree is officially "an implementation detail subject to change without notice". If they provided the code directly, it helps customers to ignore that advice. That could lead to more friction / bad press when customer code breaks as a result on an unannounced change to sun.* code.
Where can I find a comprehensive version of source code?
You can find it in the OpenJDK 6 / 7 / 8 repositories and associated download bundles:
http://hg.openjdk.java.net/jdk6/jdk6 - http://download.java.net/openjdk/jdk6/
http://hg.openjdk.java.net/jdk7/jdk7 - http://download.java.net/openjdk/jdk7/
http://hg.openjdk.java.net/jdk8/jdk8
Now for the part about "learning Java deeply".
First, I think you are probably going about this learning in a "suboptimal" fashion. Rather than reading the Java class library, I think you should be reading books on java and design patterns and writing code for yourself.
To the specifics:
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right?
At the point that the handler calls than method, it is calling it on an instance of the subclass. So finding the right method is handled by the JVM ... just like any other polymorphic dispatch.
The tricky part is how you got the instance of the sun.net.www.protocol.* handler class. And that happens something like this:
When a URL object is created, it calls getURLStreamHandler(protocol) to obtain a handler instance.
The code for this method looks to see if the handler instance for the protocol already exists and returns that if it does.
Otherwise, it sees if a protocol handler factory exists, and if it does it uses that to create the handler instance. (The protocol handler factory object can be set by an application.)
Otherwise, searches a configurable list of Java packages to find a class whose FQN is package + "." + protocol + "." + "Handler", loads it, and uses reflection to create an instance. (Configuration is via a System property.)
The reference to handler is stored in the URL's handler field, and the URL construction continues.
So, later on, when you call openConnection() on the URL object, the method uses the Handler instance that is specific to the protocol of the URL to create the connection object.
The purpose of this complicated process is to support URL connections for an open-ended set of protocols, to allow applications to provide handlers for new protocols, and to substitute their own handlers for existing protocols, both statically and dynamically. (And the code is more complicated than I've described above because it has to cope with multiple threads.)
This is making use of a number of design patterns (Caches, Adapters, Factory Objects, and so on) together with Java specific stuff such as the system properties and reflection. But if you haven't read about and understood those design patterns, etcetera, you are unlikely to recognize them, and as a result you are likely to find the code totally bamboozling. Hence my advice above: learn the basics first!!
Take a look at URL.java. openConnection uses the URLStreamHandler that was previously set in the URL object itself.
The constructor calls getURLStreamHandler, which generates a class name dynamically and loads, and the instantiates, the appropriate class with the class loader.
But URLStreamHandler is a abstract class and method openConnection()
is not implement in it so when handler calls this method, it should go
to find a subclass who implement this method, right?
It has to be declared or abstract or implemented in URLStreamHandler. If you then give an instance of a class that extends URLStreamHandler with type URLStreamHandler and call the openConnection() method, it will call the one you have overriden in the instance of the class that extends URLStreamHandler if any, if none it will try to call the one in URLStreamHandler if implemented and else it will probably throw an exception or something.