Where to instantiate interface in Nunit test - c#

I think theres something really simple I'm missing so I apologize in advance. I'm trying to test an interface with Nunit. The interface is implemented by a class derived from a base class and I'm using Castle Windsor for IOC. I simply dont know where to assign the interface in the derived test class.
Here is the base test class
[TestFixture]
public class BaseTest
{
protected ISession session;
[SetUp]
public void setup() {
NHibernateConfig.Init(
MsSqlConfiguration.MsSql2008.ConnectionString(
builder =>
builder.Server("localhost")
.Database("Db_test")
.TrustedConnection()),
RebuildDatabase());
session = NHibernateConfig.CreateAndOpenSession();
}
[Test]
public void Shoud_Test_Connection(){
// testing connection via setup fixture
}
[TearDown]
public void TearDown(){
if (session != null)
session.Dispose();
}
private Action<Configuration> RebuildDatabase() {
return config => new SchemaExport(config).Create(false, true);
}
}
here is the derived test class
[TestFixture]
public class RepositoryTest : BaseTest
{
IRepository repository;
[SetUp]
public void Setup(){
// I think the interface should get assigned
// in here somehow....
}
[Test]
public void Should_Create_And_Read(){
var post = CreatePost();
var actual = (IList) repository.GetAll();
Assert.Contains(post, actual);
Assert.AreEqual(1, actual.Count);
}
}
I have the repository registered in my windsor container and works fine in all my controllers, just cant figure out how to test the interface. My only solution is to assign the interface a concrete implementation in the setup method but I'm wondering if I'm suppose to use DI to handle that somehow.

Ask and you shall receive :)
You need a reference to your container in your test and you need to call .Resolve() I believe that is what Castle calls their method but I could be wrong.
In order to get a reference to your container in your test you need to create your container at some point. I am not really a Castle expert but check out the code on this page looks like a pretty simple example on how to new up a container and resolve a dependency
http://stw.castleproject.org/Windsor.MainPage.ashx

Related

Faking a data member that is created in the constructor

I have the following class:
public class ExampleClass
{
private readonly Service service;
public ExampleClass()
{
service = new Service();
}
private void ExecuteProcess()
{
var request = Transfer.RequestParameters;
service.SyncMethod(request);
}
}
I'm trying to fake the private readonly Service service, that is created in the constructor, because I want to ignore the call to service.SyncMethod(request).
Does anyone know how I can do this?
you can use Typemock's Isolator for faking the Service instance and for invoking the private method,for example:
[TestMethod]
public void TestMethod1()
{
Service faked = Isolate.Fake.NextInstance<Service>(Members.ReturnRecursiveFakes, ConstructorWillBe.Called);
ExampleClass exClass = new ExampleClass();
Isolate.WhenCalled(() => faked.SyncMethod(null)).IgnoreCall();
Isolate.Invoke.Method(exClass, "ExecuteProcess");
}
Provide a parameterized constructor as follows:
public ExampleClass(Service obj)
{
service = obj;
}
Then you could mock and pass the service object to the above constructor & test the function.
It is also recommended to code against an interface, in your case, create an IService, implement it in Service. Then you could inject the interface into the ExampleClass instead of the concrete implementation.
I think you should use something called 'Dependency injection'. This can be done quite easily with for example Ninject or Unity.
The result is that you do not create the service in ExampleClass, but instead pass an object of type IService to the constructor.
The interface has a method SyncMethod.
You let Service implement interface IService. You create a TestService or something that also implements IService.
In your TestService object you can make an empty implementation of the method SyncMethod to ignore it.
Your class in its current state is too tightly coupled to the dependent service, making it difficult (but not impossible) to mock dependencies to be able to test the class in isolation.
First classes should depend on abstractions and not on concretions. So abstract the Service behind an interface to allow for it to be more flexible when maintaining and testing your code in isolation.
For example
public interface IService {
void SyncMethod(RequestParameters request);
}
public class Service : IService {
//..code removed for brevity
}
Then refactor your class to follow the Explicit Dependencies Principle. This approach is known as "constructor injection".
public class ExampleClass {
private readonly IService service;
public ExampleClass(IService servic) {
this.service = service;
}
private void ExecuteProcess() {
var request = Transfer.RequestParameters;
service.SyncMethod(request);
}
}
In production, the actual dependency will be registered with the dependency container in the composition root and when the class is being resolved, the dependencies will be realized and injected into the dependent class.
This also allows for mocks/fakes/stubs to be used during testing either manually or with a mocking framework/tool of your choice.

How can I use windsor to give me an instance of an object that isn't registered?

So I have windsor set up and all of my services registered. I have a class that requires these services in the ctor, but this class isn't registered with windsor as it does not have an interface and I don't want to give it one for the sake of dependency resolution. What I'm really interested in, is having windsor resolve and inject my registered dependencies and hand me back an initialized class -- basically a factory.
The problem that I'm running into is that windsor throws because the dependent class has not been registered:
void Main()
{
var container = new WindsorContainer();
container.Register(Component
.For<ITestInterface>()
.ImplementedBy<TestImpl>()
.LifestyleTransient());
var c = container.Resolve<TestClass>(); // throws because TestClass isn't registered
c.Run();
}
public class TestClass
{
private ITestInterface _d;
public TestClass(ITestInterface d)
{
_d = d;
}
public void Run()
{
_d.Do();
}
}
public interface ITestInterface
{
void Do();
}
public class TestImpl : ITestInterface
{
public void Do()
{
Console.WriteLine("done");
}
}
What I don't want to end up doing, is something like this:
var dependency1 = container.Resolve<ITestInterface>();
var c = new TestClass(dependency1);
c.Run();
Because now we're in service locator territory. But more importantly, classes that have several dependencies...well that could get tedious.
How can I get windsor to have the desired factory effect? Or is this even possible with Windsor? I recall this being possble with Ninject.
So the popular response seems to be "Just register the component" which I really don't like at all because for such a simple use case, I could end up with a config class with hundreds of unnecessary registrations. That's kind of silly. So in the meanwhile, until I discover some built in functionality for this, I've create a cheesy extension that should land me somewhere in the middle. This extension simply takes the type, registers it for you and then tries to resolve it. That way, it's leveraging Windsor's own ctor resolution logic:
public static class WindsorExtentions
{
public static T Construct<T>(this IWindsorContainer container)
where T : class
{
if (!container.Kernel.HasComponent(typeof(T)))
container.Register(Component.For<T>());
var instance = container.Resolve<T>();
return instance;
}
}
What I would really like to do is register it, resolve it, then unregister it, but it appears that the RemoveComponent method has been removed in 3.0. This should be fine in the meanwhile. It obviously isn't all-inclusive with use cases, but when you have loads of proxy classes that have several required dependencies to be injected, I think this helps.
Usage:
var myClassWithDependencies = myContainer.Construct<MyClassWithDependencies>();
public class MyClassWithDependencies
{
public MyClassWithDependencies(
IFacebookClient facebookClient,
IGooglePlusClient googlePlusClient,
ITwitterClient twitterClient,
ISalesforceClient salesforceClient,
IReportRepository reportRepo,
IUserRepository userRepo)
{
}
}

Xunit test context to run only once per class

I have my test class inheriting from a base, which basically calls a Context method before the Facts, but xunit is calling context once per fact:
public class running_some_test : TestContext<ThingImTesting>
public void Because()
[Fact]
public void it_should_do_something()
[Fact]
public void it_should_do_more()
public void Context()
I know I could use the IClassFixture , but the TestContext inheritance is providing the test with Because() and Context() methods to override along with the type of SUT. I also think the IClassFixture is too generic, my context is very specific for each test criteria, and SetFixture seems more like a generic set up. Does anyone have a similar pattern that I could follow?
xunit instantiates a new object from your test class per fact. This is done to give each test it's own environment and to make parallelism easier. The recommended way to share context between tests in the same test class is the IClassFixture<T> interface.
You can add you Because() method to your fixture class if you need access to it in your tests. It looks to me like you're already doing something similar, only you're doing it with inheritance as opposed to composition. You can read up on how the interface works here: https://xunit.github.io/docs/shared-context.html#class-fixture
Example from the link:
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
Db = new SqlConnection("MyConnectionString");
// ... initialize data in the test database ...
}
public void Dispose()
{
// ... clean up test data from the database ...
}
public SqlConnection Db { get; private set; }
}
public class MyDatabaseTests : IClassFixture<DatabaseFixture>
{
DatabaseFixture fixture;
public MyDatabaseTests(DatabaseFixture fixture)
{
this.fixture = fixture;
}
// ... write tests, using fixture.Db to get access to the SQL Server ...
}
xunit injects the fixture class via your constructor, so you can do stuff the way you do them now, only you access fixture members via the injected parameter instead of via your super class.

moq a class that IS derived from the same interface as the one being moq'd

I am new to the whole MOQ movement... which by the way is pretty cool ... and I am mocking all kinds of stuff now..
Anyway, I ran into this scenario and was wondering how to go about mocking it up.
I have an class that implements the interface that I want to mock:
public interface ImyInterface
{
void doit();
}
public abstract class myBase<TChannel> : ICommunicationObject, IDisposable where TChannel : class
{
protected TChannel Channel { get; private set; }
// ICommunicationObject implementation not shown
}
public class myIIntClass : myBase<ImyInterface>, ImyInterface
{
public myIIntClass()
{
}
public void doit()
{
Channel.doit();
}
}
I think my moq test doesn't mock anything... but I am unsure and hoping to get some insight on how to either write it correctly or refactor my class:
Here is my current MOQ test:
MyClass myClass = null;
Mock<ImyInterface> moq = new Mock<ImyInterface>();
moq.Setup(x => x.doit());
myClass = (MyClass)moq.Object;
myClass.doit();
moq.VerifyAll();
Thanks from one moqer to another... :-)
I feel like maybe you're missing the point of mocking here. You mock dependencies that exist in a unit of work you're testing. So, let's say I'm testing doit here in the concrete implementation of MyClass; I want to make sure it works right. Now, let's say that method has a dependency to another class; it calls a method on it that returns a boolean value. What I want to do is mock that class because I want to make sure that MyClass.doit behaves right when it returns true and when it returns false.
See, in the example above, what I've done is ensured that no other dependencies are affecting the code flow of MyClass.doit; I'm forcing MyClass.doit down a very specific path; I want to test that path.
The code you've created literally performs nothing because it just executes the mocked up method.
You don't mock/stub the unit under test. If you are testing the doIt(), you don't mock that, you mock its (or class) dependencies.

Mocks to verify interaction

Typically when I need to mock out a class for testing, I'll use a library such as Rhino Mocks. Here I have a class called MyService that expects a IEmailSender.
public class MyService
{
private readonly IEmailSender sender;
public MyService(IEmailSender sender)
{
this.sender = sender;
}
public void Start()
{
this.sender.SendEmail();
}
}
If I needed to test the interaction between these two objects, my test would look something like this:
[TestMethod]
public void Start_Test_Using_Rhino_Mocks()
{
IEmailSender emailSender = MockRepository.GenerateMock<IEmailSender>();
MyService service = new MyService(emailSender);
service.Start();
emailSender.AssertWasCalled
(
x => x.SendEmail(),
c => c.Repeat.Once()
);
}
In the test above, I'm using Rhino Mocks to generate the mock and assert that the SendEmail() method was called once.
But what if I could not use Rhino Mocks and had to create manual mocks?
public class MockEmailSender : IEmailSender
{
public void SendEmail()
{
}
}
[TestMethod]
public void Start_Test_Using_Manual_Mocks()
{
MockEmailSender emailSender = new MockEmailSender();
MyService service = new MyService(emailSender);
service.Start();
// How do I test the interaction?
}
With the mock that I created manually, how would I verify that the SendEmail() method was called? I could put my assertions in the SendEmail() method of the mock, but that would make the test hard to understand since I don't immediately see what's going on when I look at the test.
A very simple solution would have your manual mock just be a stateholder, with counters for the calls to each method. But it's fragile ...
public class MockEmailSender : IEmailSender
{
public int SendCount = 0;
public void SendMail(...)
{
SendCount++;
}
// ... other IEmailSender methods ...
}
Then just query SendCount after making your method call, and making sure that it's == 1.
Remember, Rhino Mocks is creating this dynamically for you -- if you do it manually you have to react to interface changes before compile time, by hand.
I think that you have no other option than setting a flag in "SendEmail()", and checking that flag from the test throgh a new method of MockEmailSender like "sendMailWasInvoked()" or something like this (which is in fact a kind of "verify").
You can extend this to count the number of invokations, parameters...
well i would advise against creating any manual Mocks (because if you add new method to interface, it gets broken).
if you really have to do it, when expose some counter/bool in your MockEmailSender and you can Assert it later on.
Assert.IsTrue(emailSender.IsCalled)

Categories

Resources