Stubbing static methods in MSpec - testing

I'm trying to test a class that utilizes a repository class that is interfaced with through static methods. The actually repository interacts with a database. I do not want to setup a database in Test, I only to make sure that the repository methods are called. In the RSpec world I would do something like allow(NodeRepository).to receive(:create).and_return(true). Is there a similar feature in MSpec or some other .NET testing tools.

It's not possible to stub static methods in. NET without extra testing tools like TypeMock Isolator. All freely available mocking tools on .NET use dynamic proxies that cannot hook into non-virtual methods (which static methods are).

Related

How to extend java classes on in Python with JPype as its interfacing mechanism with java?

I use JPype to build a SOAP client in my python based test platform. However, I need to extend a Java class to make a call like this:
Like
void process(Context parameter)
The type Context here is a class and to give an implementation, I need to extend Context in python using JPype.
class MyContext extends Context { //override the methods}
With JProxy functionality (in JPype), I'm able to "implement" java interfaces.
But I want to extend a class not an interface. Any help is appreciated.
This very much a limitation. JPype does not allow sub-classing.
sourceforge link
Changed the SOAP method to accept an interface in the API contract.
JPype is an effort to allow Python programs full access to Java class libraries. This is achieved not through re-implementing Python, as Jython/JPython has done, but rather through interfacing at the native level in both virtual machines.
Eventually, it should be possible to replace Java with Python in many, though not all, situations. JSP, Servlets, RMI servers and IDE plugins are all good candidates.
Once this integration is achieved, a second phase will be started to separate the Java logic from the Python logic, eventually allowing the bridging technology to be used in other environments, i.e. Ruby, Perl, COM, etc ..

Creating a Rust library with multiple modules which all are a unified API

I have an exercise library to learn Rust. This library provides two kinds of methods:
core methods which should be in a file called renderay_core.rs.
shape methods which use the core methods to have a higher abstraction/more concrete implementation of the core methods; convenience methods for "often used" cases. These should be in a file called renderay_shapes.rs.
I also want to have unit tests in them as submodules.
I thought of something like:
renderay.rs is the library source [lib] path="src/renderay.rs"
renderay_core.rs is a module which is loaded into renderay.rs as public(?) to yield its API
renderay_shapes.rs is also a module within renderay.rs but also imports renderay_core.rs to its core API
If I load this crate as a dependency, I would like to have the API of renderay_core.rs and renderay_shapes.rs available.
I'm sure it is a trivial task, but I have a hard time getting my head around the module mechanics coming from Java and C. I already read the crates and modules documentation. How to setup such a structure and compile it successfully?

Is it bad idea to use Dependency Injection objects in unit tests?

I am not sure if what i am doing is actually the "correct" way of doing unit tests with DI. Right now i ask my ViewModelLocator to actually create all the instances i need, and just get the instance i need to test, which makes it very simple to test a single instance because lets asume that Receipt needs a Reseller object to be created, reseller needs a User object to be created, user need some other object to be created, which creates a chain of objects to create just to test one single instance.
With di usally interfaces will get mocked and parsed to the object which you would like to create, but how about simple Entities/ViewModels?
Whats the best practice to do unit testing with DI involved?
public class JournalTest
{
private ReceiptViewModel receipt;
private ViewModelLocator locator;
[SetUp]
public void SetUp()
{
locator = new ViewModelLocator();
receipt = SimpleIoc.Default.GetInstance<ReceiptViewModel>();
}
[TearDown]
[Test]
public void CheckAndCreateNewJournal_Should_Always_Create_New_Journal()
{
receipt.Sale.Journal = null;
receipt.Sale.CheckAndCreateNewJournal();
Assert.NotNull(receipt.Sale.Journal);
}
}
First, you aren't using Dependency Injection in your code. What you have there is called Service Locator (Service Locators create a tight coupling to the IoC/Service Locator and makes it hard to test).
And yes, it's bad (both Service Locator and Dependency Injection), because it means: You are not doing a UnitTest, you are doing an integration Test.
In your case the ReceiptViewModel will not be tested alone, but your test also tests the dependencies of ReceiptViewModel (i.e. Repository, Services injected etc.). This is called an integration test.
A UnitTest has to test only the class in question and no dependencies. You can achieve this either by stubs (dummy implementation of your dependencies, assuming you have used interfaces as dependencies) or using mocks (with a Mock framework like Moq).
Which is easier/better as you don't have to implement the whole class, but just have to setup mocks for the methods you know that will be required for your test case.
As an additional note, entities you'll got to create yourself. Depending on your UnitTest framework, there may be data driven tests (via Attributes on the test method) or you just create them in code, or if you have models/entities used in many classes, create a helper method for it.
View Models shouldn't be injected into constructor (at least avoided), as it couples them tightly
Units tests should run quickly and should be deterministic. That means you have to mock/stub everything that brokes these two rules.
The best way to mock/stub dependancies is to inject them. In the production, classes are assembled by DI framework, but in unit tests you should assemble them manually and inject mocks where needed.
There is also a classic unit test approach where you stub/mock every dependency of your class, but it's useless since you don't gain anything by that.
Martin Fowler wrote great article about that: link
You should also read Growing Object-oriented software: Guided by tests. Ton of useful knowledge.

Rhino mock a singleton class

I want to test my controller that depends on a hardware C# class, not an interface.
It's configured as a singleton and I just can't figure out how to RhinoMock it.
The hardware metadata (example) for the dependent class:
namespace Hardware.Client.Api
{
public class CHardwareManager
{
public static CHardwareManager GetInstance();
public string Connect(string clientId);
}
}
and in my code I want this something like this to return true, else I get an exception
if( !CHardwareManager.GetInstance().Connect("foo") )
I mock it using:
CHardwareManager mockHardwareMgr MockRepository.GenerateMock<CHardwareManager>();
But the Connect needs a GetInstance and the only combination I can get to "compile" is
mockHardwareMgr.Expect (x => x.Connected ).Return(true).Repeat.Any();
but it doesn't correctly mock, it throws an exception
but this complains about typing the GetInstance
mockHardwareMgr.Expect (x => x.GetInstance().Connected).Return(true).Repeat.Any();
So my problem - I think - is mocking a singleton. Then I have no idea how to make my controller use this mock since I don't pass the mock into the controller. It's a resource and namespace.
90% of my work requires external components I need to mock, most times I don't write the classes or interfaces, and I'm struggling to get them mocked and my code tested.
Any pointers would be welcome.
Thanks in advance (yes, I've been searching through SO and have not seen something like this. But then, maybe my search was not good.
The usual way to avoid problems with mocking external components is not to use them directly in your code. Instead, define an anti-corruption layer (usually through an interface that looks like your external component) and test your code using mocked implementation of this interface. After all, you're testing your own code, not the external one.
Even better way is to adjust this interface to your needs so it only exposes stuff that you actually need, not the whole API the external component provides (so it's actually an Adapter pattern).
External components are tested using different approaches: system testing, in which case you don't really mock them, you use the actual implementation.
Usually when you try to get Rhino Mocks to do something which feels unnatural and Rhino growls, this is a good sign that your approach is not the right one. Almost everything can be done using simple interface mocking.
As Igor said RhinoMocks (and most other free mocking frameworks, e.g. Moq) can only mock interfaces.
For mocking classes try (and pay) TypeMock.
For mocking singletons see my answer to:
How to Mock a Static Singleton?
Yes, I'm somewhat undermining the common understanding of what's deemed testable and thus "good" code. However I'm starting to resent answers like "You're doing it wrong. Make everything anew." for those answers don't solve the problem at hand.
No, this is not pointing at Igor, but at many others in similar threads, who answered "Singletons are unmockable. (Make everything anew.)".

Scripting Eclipse with Rhino: classloader belongs to the plugin providing Rhino, not the plugin using it

I am using Rhino to script an Eclipse (RCP) application. The problem is that from Javascript I only have access to classes available to the plugin that provides Rhino, and not to all the classes available to the plugin that runs the scripts.
The obvious answer would be to put Rhino in the scripting plugin, but this doesn't work because it's already provided by one of the application's own plugins (which also provides things I need to script) and Eclipse always uses this version instead of the version closer to hand.
Is there a way to change the classloader used by Rhino
or is it possible to ensure that Eclipse loads the Rhino classes from one plugin rather than another?
Thanks to Thilo's answer I used this:
import net.weissmann.tom.rhino.Activator; // Plugin activator class
import org.mozilla.javascript.tools.shell.Main;
public class JSServer extends Thread {
//[...]
public void run() {
// recent versions of the Main class kindly export
// the context factory
Main.shellContextFactory.initApplicationClassLoader(
Activator.class.getClassLoader()
) ;
//[...]
}
Is there a way to change the classloader used by Rhino
Rhino should be using the current Thread's ContextClassLoader. Try Thread.setContextClassLoader (don't forget to restore it).
If that does not work, maybe you can create your own Rhino ContextFactory:
public final void initApplicationClassLoader(java.lang.ClassLoader loader)
Set explicit class loader to use when searching for Java classes.
I don't know Rhino specifics, but you could consider using Eclipse "buddy classloading" with the "registered" policy.
Rhino's plug-in (net.weissmann.tom.rhino, say) would declare itself "open to extension" by specifying Eclipse-BuddyPolicy: registered in its MANIFEST.MF. Plug-ins with classes that Rhino should be able to see would specify Eclipse-RegisterBuddy: net.weissmann.tom.rhino and would need a bundle-level dependency on net.weissmann.tom.rhino.
http://www.eclipsezone.com/articles/eclipse-vms/
http://wiki.eclipse.org/index.php/Context_Class_Loader_Enhancements#Technical_Solution