Generated moles type for a static internal class is not accessible in test class - moles

I am trying to get access to an internal static class to override some of its methods so that I can test classes that depend on that class
From what I read that should be possible but I am not obviously not understanding everything as even a simple example seems to fail to generate a mole type for the internal static class.
I have two classes in a namespace and assembly
namespace SimpleClassToTest
{
public class Class1
{
public string SayOla() { return Class2.ReturnMe("Ola"); }
}
}
namespace SimpleClassToTest
{
internal static class Class2
{
static public string ReturnMe(string m)
{
return m;
}
}
}
In AssemblyInfo.cs I also have
[assembly: InternalsVisibleTo("SimpleClassToTest")]
[assembly: InternalsVisibleTo("SimpleClassToTest.Moles")]
In the test project I have a single test class
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SimpleClassToTest;
using SimpleClassToTest.Moles;
namespace SimpleClassToTest.Moles
{
[TestClass]
public class UnitTest1
{
public UnitTest1()
{
}
[TestMethod]
[HostType("Moles")]
public void TestMethod1()
{
Class1 c1 = new Class1();
Assert.AreEqual(c1.SayOla(), "Ola");
MClass2.ReturnMeString = (ignored) => { return "ReturnMe"; };
Assert.AreEqual(c1.SayOla(), "ReturnMe");
}
}
}
Unfortunately that is not compiling. The error is
UnitTest1.cs(25,13): error CS0122: 'SimpleClassToTest.Moles.MClass2' is inaccessible due to its protection level
Any tips to get this going would certainly be appreciated!
Thanks!
Peter
PS Tried this both on VS2008 and on VS2010 with moles version Microsoft Moles v0.94.51023.0
(Edit : From Comment Below)
As a workaround, in the unit test:
Type mClass2Type = typeof(SimpleClassToTest.Moles.MClass1)
.Assembly.GetType("SimpleClassToTest.Mole‌​s.MClass2");
PropertyInfo returnMeProp = mClass2Type.GetProperty("ReturnMeString");
Microsoft.Moles.Framework.MolesDelegates.Func<String, String> molesDelegate =
(ignore) => { return "ReturnMe"; };
returnMeProp.SetValue(mClass2Type, molesDelegate, null);
Assert.AreEqual(c1.SayOla(), "ReturnMe");

If your assembly under test is strongly signed, then the moles assembly is also strongly signed, and you must specify the public key in the InternalsVisibleTo attribute. See the section "Code Generation and Compilation" of the moles reference manual for details.
Here is a quote that might be relevant:
... use this snippet as a
starting point to add InternalsVisibleTo attribute to your project.
[assembly: InternalsVisibleTo(“FileSystem.Moles, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e92decb949446f688ab9f6973436c535bf50acd1fd580495aae3f875aa4e4f663ca77908c63b7f0996977cb98fcfdb35e05aa2c842002703cad835473caac5ef14107e3a7fae01120a96558785f48319f66daabc862872b2c53f5ac11fa335c0165e202b4c011334c7bc8f4c4e570cf255190f4e3e2cbc9137ca57cb687947bc”)]

Related

Test fixture inheritance and ignored base test fixtures

I have a set of base tests that are used to test multiple implementations of a interface. The way I modelelled this was by creating a base text fixture with a [Ignore] attribute.
[TestFixture]
[Ignore]
public class BaseTests
{
// Use your imagination for the actual name
public virtual ITestableThing GetConcrete()
{
return null;
}
// All of my unit tests here
}
And then I write a subclass for each interface implementation:
public class ConcreteThingTests : BaseTests
{
public override ITestableThing GetConcrete()
{
return new ConcreteThing();
}
}
This works well, as I have all of the tests for ALL implementations in one place, and the sub classes just specify the implementation.
The problem is that I have to put the [Ignore] attribute on the base class, or NUnit will try to run the tests (and fail).
Because of this, my test results are always cluttered up with a set of Ignored tests, and while it's not a big deal, I thought there might be a better pattern for this that avoids having to ignore tests.
So, am I implementing test fixture inheritance wrong?
The NUnit test runner appears to ignore the base class if it is marked abstract:
public abstract class BaseTests
{
}
You would normally set the test attributes on your concrete test classes, not the base class.
Since you seem to test the same functionality for multiple classes, you could skip the whole test hierarchy and inject the concrete classes to be tested to that test-baseclass.
To do that with NUnit you could use the TestCaseSource attribute with a class factory method as a parameter. An example of that can be found here: How to pass dynamic objects into an NUnit TestCase function?
Making up some code for your particular case, it could be like shown below:
/// <summary>
/// Earlier known as your BaseTests class
/// </summary>
[TestFixture]
public class TestOfConcreteImplementationsOfInterface
{
[TestCaseSource("CreateConcretes")]
[Test]
public void VerifyImplementations(IWhatever thing)
{
int input = 42;
int result = thing.DoSomething(input);
Assert.That(result, Is.EqualTo(input));
}
/// <summary>
/// Factory method for the concrete classes. If you want this in a seperate class, you can do that too using the
/// ctor public TestCaseSourceAttribute(Type sourceType, string sourceName);
/// </summary>
public IEnumerable<IWhatever> CreateConcretes
{
get
{
yield return new A();
yield return new B();
}
}
}
public interface IWhatever
{
int DoSomething(int x);
}
public class A : IWhatever
{
public int DoSomething(int x)
{
return x;
}
}
public class B : IWhatever
{
public int DoSomething(int x)
{
return x;
}
}

Testing multiple interface implementations with same tests - JUnit4

I want to run the same JUnit tests for different interface implementations. I found a nice solution with the #Parameter option:
public class InterfaceTest{
MyInterface interface;
public InterfaceTest(MyInterface interface) {
this.interface = interface;
}
#Parameters
public static Collection<Object[]> getParameters()
{
return Arrays.asList(new Object[][] {
{ new GoodInterfaceImpl() },
{ new AnotherInterfaceImpl() }
});
}
}
This test would be run twice, first with the GoodInterfaceImpl then with the AnotherInterfaceImpl class. But the problem is I need for most of the testcases a new object. A simplified example:
#Test
public void isEmptyTest(){
assertTrue(interface.isEmpty());
}
#Test
public void insertTest(){
interface.insert(new Object());
assertFalse(interface.isEmpty());
}
If the isEmptyTest is run after the insertTest it fails.
Is there an option to run automatically each testcase with a new instance of an implementation?
BTW: Implementing a clear() or reset()-method for the interface is not really an options since I would not need it in productive code.
Here is another approach with the Template Method pattern:
The interface-oriented tests go into the base class:
public abstract class MyInterfaceTest {
private MyInterface myInterface;
protected abstract MyInterface makeContractSubject();
#Before
public void setUp() {
myInterface = makeContractSubject();
}
#Test
public void isEmptyTest(){
assertTrue(myInterface.isEmpty());
}
#Test
public void insertTest(){
myInterface.insert(new Object());
assertFalse(myInterface.isEmpty());
}
}
For each concrete class, define a concrete test class:
public class GoodInterfaceImplTest extends MyInterfaceTest {
#Override
protected MyInterface makeContractSubject() {
// initialize new GoodInterfaceImpl
// insert proper stubs
return ...;
}
#Test
public void additionalImplementationSpecificStuff() {
...
}
}
A slight advantage over #Parameter is that you get the name of the concrete test class reported when a test fails, so you know right away which implementation failed.
Btw, in order for this approach to work at all, the interface must be designed in a way which allows testing by the interface methods only. This implies state-based testing -- you cannot verify mocks in the base test class. If you need to verify mocks in implementation-specific tests, these tests must go into the concrete test classes.
Create a factory interface and implementations, possibly only in your test hierarchy if you don't need such a thing in production, and make getParameters() return a list of factories.
Then you can invoke the factory in a #Before annotated method to get a new instance of your actual class under test for each test method run.
Just in case somebody reaches here(like I did), looking for testing multiple implementations of the same interface in .net you could see one of the approaches that I was using in one of the projects here
Below is what we are following in short
The same test project dll is run twice using vstest.console, by setting an environment variable. Inside the test, (either in the assembly initialize or test initialize) register the appropriate implementations into a IoC container, based on the environment variable value.
In Junit 5 you could do:
#ParameterizedTest
#MethodSource("myInterfaceProvider")
void test(MyInterface myInterface) {}
static Stream<MyInterface> myInterfaceProvider() {
return Stream.of(new ImplA(), new ImplB());
}
interface MyInterface {}
static class ImplA implements MyInterface {}
static class ImplB implements MyInterface {}

Testing Ninject project installed via Nuget - WebActivate behavior

I am trying to create a NUnit test for a project that uses Ninject. The Ninject was installed via Nuget, so the Configuration clas looks similar to this simplified version:
[assembly: WebActivator.PreApplicationStartMethod(typeof(NinjectMVC3), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(NinjectMVC3), "Stop")]
public static class NinjectMVC3
{
private static readonly Bootstrapper Bootstrapper = new Bootstrapper();
private static IKernel _kernel;
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
Bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
Bootstrapper.ShutDown();
}
}
I want those methods to be called in my startup test class. I tried:
[TestFixture]
public class TestBase
{
[SetUp]
public void Setup()
{
NinjectMVC3.Startup();
}
[TearDown]
public void TearDown()
{
NinjectMVC3.TearDown();
}
}
It will not work because I am trying to manually call methods that are managed by WebActivator. So I am looking for a way to instruct WebActivator to call those methods in a 'right time'. Let me remind you that there are two project that I am dealing with, one is a MVC Web Project (and it uses WebActivator for Ninject), and the other one is a Test project for my MVC Web Project. I tried to call WebActivator by changing implementation of my Setup method:
[SetUp]
public void Setup()
{
WebActivator.ActivationManager.Run();
}
It doesn't work. As far As I understand underneath this call WebActivator should do something similar to:
foreach (var assemblyFile in Directory.GetFiles(HttpRuntime.BinDirectory, "*.dll")) {
var assembly = Assembly.LoadFrom(assemblyFile);
foreach (PreApplicationStartMethodAttribute preStartAttrib in assembly.GetCustomAttributes(
typeof(PreApplicationStartMethodAttribute),
inherit: false)) {
preStartAttrib.InvokeMethod();
}
}
So I guess that it is unable to find an assembly. So the question is - how can I order WebActivator to scan thru some additional assembly and fire some methods in a 'right time'. Or maybe I am mislead here, and in order to test my Ninject project I should take a different approach?
I am able to test my solutions w/o WebActivator, but because it is widely used recently, I am keen to learn how to deal with it and force it to do things that I want.
I would avoid using WebActivator from your test project as it will not play well outside of asp.net.
If you want to test the setup of your Ninject kernel than i would make the CreateKernel() method public and call that from your Setup() method.
public static IKernel CreateKernel()
...
[SetUp]
public void Setup()
{
NinjectMVC3.CreateKernel();
}
Unfortunately by default WebActivator looks for a "*.dll" in a c:\tmp... directory, and due to that it is unable to find project libriaries that are included to the solution.
I ended up geting the source code and adding a following code to the ActivationManager class:
public static void AddAssembly(Assembly assembly)
{
if (_assemblies == null)
{
_assemblies = new List<Assembly>();
}
_assemblies.Add(assembly);
}
And in test class:
private const int PreStartInitStage_DuringPreStartInit = 1;
[SetUp]
public void Setup(){
WebActivator.ActivationManager.AddAssembly(Assembly.GetAssembly(typeof(NinjectMVC3)));
typeof(BuildManager).GetProperty("PreStartInitStage", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, PreStartInitStage_DuringPreStartInit, null);
WebActivator.ActivationManager.RunPreStartMethods();
Kernel = NinjectMVC3.GetKernel();
}
This is ugly code, and I hope to see one day a better approach.

MVC2 & Ninject2 - Controllers not resolving dependency

I foolishly decided to try something new on a Friday job!
So I have used NuGet to add Ninject.Web.Mvc 2.2.x.x to my .Net MVC2 project.
I've altered my Global.asax.cs
using System.Web.Mvc;
using System.Web.Routing;
using IntegraRecipients;
using Mailer;
using Ninject;
using Ninject.Web.Mvc;
using Ninject.Modules;
namespace WebMailer
{
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Mail", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
{
return new StandardKernel(new INinjectModule[] { new MailModule()});
}
internal class MailModule : NinjectModule
{
public override void Load()
{
Bind<IMailing>().To<Mailing>();
Bind<IMailingContext>().To<MailingContext>();
Bind<IRecipientContext>().To<RecipientContext>();
}
}
}
}
and I've created a controller like so...
using System.Linq;
using System.Web.Mvc;
using WebMailer.Models;
namespace WebMailer.Controllers
{
[ValidateInput(false)]
public class MailController : Controller
{
private readonly IMailingContext _mailContext;
private readonly IRecipientContext _integraContext;
public MailController(IMailingContext mail,IRecipientContext integra)
{
_mailContext = mail;
_integraContext = integra;
}
public ActionResult Index()
{
return View(_mailContext.GetAllMailings().Select(mailing => new MailingViewModel(mailing)).ToList());
}
}
}
But the controller is still insisting that
The type or namespace name 'IRecipientContext' could not be found (are you missing a using directive or an assembly reference?)
and
The type or namespace name 'IMailingContext' could not be found (are you missing a using directive or an assembly reference?)
My google-fu has failed me and I really hope this is just a silly typo/missing line thing
Thanks in advance
P
Ninject does not change the way assemblies are compiled! It deos not magically add references to other assemblies or add using directives. If you are using interfaces from other assemblies you have to add a using directive and a reference to this assembly.
All Ninject is about is to wire up your application at runtime.
I am have what appears to be a similar problem.
I have a simple WPF Window project with the compiled Ninject.dll linked in. However, the following is giving me errors...
using Ninject;
namespace CatalogueManager
{
public class ServiceLocator
{
public IMainWindowViewModel GetMainWindowViewModel()
{
return Kernel.Get<IMainWindowViewModel>();
}
static IKernel Kernel;
static ServiceLocator()
{
Kernel = new StandardKernel(new NinjectConfiguration());
}
}
}
In particular, "Ninject" namespace and IKernel are prompting the compile time message "type or name space 'X' not found..."

NUNIT is ignoring my tests? Why?

I Have a really simple test class as below.
For some reason my test is being ignored by the GUI and coming up yellow.
I have updated the framework and runner to 2.4.8 as I thought it might have been differences between versions being the problem.
using System;
using NUnit.Framework;
namespace TestRunner
{
[TestFixture]
class TestMe
{
[Test]
public void TestBob()
{
Assert.IsTrue(true);
}
}
}
Your TestMe class needs to be public.
Here is some documentation on the requirements for classes marked with the TestFixture attribute that discusses the conditions under which a class may not be recognized as a test fixture.
You didn't specify an access modifier for your class; therefore, your class is internal by default and NUnit does not see your class.
If you specify the public access modifier for your class that contains the Tests, then it should just work:
[TestFixture]
public class TestMe
{
[Test]
public void TestBob()
{
Assert.AreEqual ("Bob", "Bob");
}
}