How to verify a statc methode in Moq - nunit

I am new to Nunit and Moq
I have a static class like this:
public static class StaticClass1
{
public static void Prepare()
{
//some logic
}
}
public static class StaticClass2
{
public static void Initialize(some_parameter)
{
//some logic
if (some_condition(some_parameter))
{
StaticClass1.Prepare();
}
}
}
I need to test the function AccountService.Initialize() in which I need to verify StaticClass1.Prepare() is being called at least once

I think that to answer this question I would say something like "You need to get experience in how to layer a project".
When unit testing a method you want to unit test that single method, and mock the dependencies, exactly as you try to do if I understand you correctly. Now it's not optimal to call static public methods from one class to another static method in another class since it makes it difficult to isolate you unit tests and what they should test (you end up with testing two completely different methods in the same unit test instead of separating the code and unit tests).
On another approach you break the D in SOLID (Dependency inversion principle) that you can read more about here -> https://en.wikipedia.org/wiki/SOLID_(object-oriented_design). You want to depend upon abstractions rather than concrete classes.
Lastly I thought that I would be a bit selfish and share a link to an article series that I have written myself. It's about Test Driven Development and uses Moq as unit testing tool and focuses on how to think when layering and unit testing a complete project (in a small scale). I'm absolute certain that it will help you understand on how to continue with you own projects and code.
It's based upon 4 articles. The first in the series is here -> http://www.andreasjohansson.eu/technical-blog/getting-started-unit-testing-a-web-project-part-1-introduction-and-setting-up-the-project/
Hope it helps!

Related

Define order of "Parallelizable" in NUnit

Im having 4 test classes inside one project (Lets call them Class A, Class B, Class C, Class D)
Each of these 3 classes have two [TestFixture("string")], which makes it to 8 tests in total.
All classes are having the [Parallelizable] parameter.
When i start the test all at once by clicking inside the Test Explorer on the name of the project and "Run", then it will start all 8 tests at the same time.
The problem here is, that it consumes a lot RAM and the tests fail because it takes too long to load and i get a timeout error (Im doing automation tests with selenium in chrome)
Now i want to define a order.
For example:
Class A and Class B should start parallel
Class C and Class D should start parallel when Class A and Class B is done
Is it possible?
I tried the parameter [Order(1)] for Class A and Class B and Order(2)] for Class C and Class D
But when i run the tests, all 8 tests start to load.
Example from my code:
[TestFixture("normalUser")]
[TestFixture("adminUser")]
[Parallelizable]
public class ImportTest
{
private IWebDriver webDriver;
private const int waitTimer = 60;
public WebDriverWait w;
public string userRole;
// Constructor
public ImportTest(string userRole)
{
this.userRole = userRole;
Console.WriteLine(userRole);
}
////-----------------------------
[SetUp]
{
}
//-------------------------------
[Test]
public void Test1()
{
Do Test
}
[Test]
public void Test2()
{
Do Test
}
//--------------------------
[TearDown]
public void CloseBrowser()
{
webDriver.Quit();
}
}
First, I'll describe what's happening...
The OrderAttribute was created in NUnit V2, before parallel tests existed. It defines the order in which tests are started. Since there was no parallelism at the time, one test had to finish before the next one started.
When parallel execution was introduced in NUnit 3, Order was not exactly broken, because it continued to start tests in the specified order. But many users perceptions were "broken", because they thought that one test would not start until the prior one finished.
Order could, of course, be changed to work like that. However, at this point, that would be a breaking change for some people, so you most likely won't see it happen until there's an NUnit 4.
So... what can you do as a workaround? I can see three options...
The simplest approach would be to make each fixture [NonParallelizable]. Then they would all run separately. You should try that first and see if the performance is acceptable to you. If you want the tests within each fixture to run in parallel, you could use [Parallelizable(ParallelScope.Children)] instead but that might break things if the tests change the state of the fixture or of any common references found in the fixture.
Alternatively, you could pick only some fixtures to mark as [NonParallelizable]. In that case, I'd do it for the ones that consume a lot of memory.
For the most effort required, you could implement ordering yourself for these classes. I'd do that by creating some sort of shared token... e.g. a lock... which each class had to acquire on startup. I'd grab the lock in the OneTimeSetUp for a fixture and release it in the onetime teardown. The locking code should be before any setup code, which acquires resources and should be released after your teardown releases those resources.
I made option 3 rather sketchy because (a) I don't know precisely how your application works and (b) I presume that you won't do it unless it's absolutely necessary.
Final advice: don't make any assumptions about the performance impact of any of these options, even the first. Measure first!

Is there any alternative to [OneTimeSetup] in Nunit?

In my existing [OneTimeSetup] method, I want to check some preconditions before running any test. But I can't do so as the object which I'll be needing to check preconditions is initialized in Base class [Setup] method. I can't initialize this earlier due to some project limitations.
So, Is there any way where I can execute some code after Base [Setup] method (to check some preconditions) and before any suite execution? I want to execute this once per suite.
[SetUpFixture]
Class GlobalSetup
{
[OneTimeSetUp]
public void OneTimeSetUp(){
setup();
CheckIfDataIsPresent(); // I can't do this here as this code needs Obj O to be initialized. which will be initialized in Base class's [Setup] methed
}
}
Public class Base
{
[Setup]
public void setUp()
{
//some code where we initialize obj O;
}
}
[TestFixture]
public class Test : Base
{
// tests to be executed
}
You already did a nice job of explaining why what you want to do won't work, so I don't have to. :-)
The problem is that each your tests needs a fresh instance of that object, so you properly create it in a [SetUp] method. You would like to ensure that it's possible to create such an object once before you run any tests.
I can only give you a non-specific answer, since you haven't given a lot of info in your example code. If you update your question, I may be able to update my answer. Here goes...
Both your tests and the check you want to perform require an instance of object o. So one approach would be to initialize o one more time in the OneTimeSetup, perform the check and then throw it away. Since you are initializing o in every test, I assume it's not expensive to do so. Say you have 100 tests. You are setting up o 100 times. So make it 101 and be done!
Alternatively, determine what is required for o to be initialized successfully and check that. For example, if it needs a file to be present, check that the file is present. If the file has to have 100 records in some format, check that it's so. Perhaps you might give us more detail about what those prerequisites are.
Finally, you might reconsider whether you really need a new instance per test. Since you suggest you would be willing to make a check once per fixture (I assume that's what you mean by suite) then perhaps you really only need one instance per fixture rather than a new one for each test.

How should I separate integration tests for an EF code first DAL and pure unit tests of the DAL clients?

Having seen some strong advice against testing EF against mocks, especially Code First, I have decided to go with integration testing against a SqlCe database dedicated to testing, and then use pure unit tests further downstream from the unit of work and repositories provided by DbContext and DbSet.
I am just unclear where to draw the line and what to test where. I know I can mock the DAL in my service layer when I am confident the DAL specific integration tests cover its insides, but what do I test in the DAL? There doesn't seem to be much point testing to see if I can save and read an object, because EF is external and already tested.
You will test your mapping and queries in DAL by using integration tests. Example:
public class Service {
private readonly IDAL _dal;
public Service(IDAL dal) {
// Not null validation here
_dal = dal;
}
public void DoSomething() {
SomeData data = FindSomeData();
// Do some logic
_dal.Commit();
}
protected virtual SomeData FindSomeData() {
return _dal.SomeData.Where(...).FirstOrDefault();
}
}
This is very simplified example showing:
Service dependent on DAL. DAL interface is passed through constructor injection.
The Service contains public DoSomething method you want to test to know if the logic is executed correctly. But this method is also dependent on DB query and DB persistence (Commit).
The query is part of your logic but executing such query is separate concern so it is handled by its own method. In more complex situation this method can be in other class injected to the Service class (repository). The key criteria for these query methods are:
They don't return IQueryable
They don't accept Expression<> as parameters
How to unit test DoSomething method:
In this simple example your test class will derive from Service class and override FindSomeData to return test data. In case of injection you would instead define fake for injected class.
You will also mock IDAL and you can verify that Commit was called
What integration test you should use:
You should create test for FindSomeData querying the real database
In general you should also have integration test for Commit but it is more difficult to achieve because the example has commit called directly from DoSomething. You don't want to test that method again and in the same time Commit method has too much generic cases because it simply flushes all changes from current context to database. I usually have separate tests for inserting, updating and deleting every entity type. When the DoSomething method does some complex modification you can split the method into two methods one handled by unit test for a real logic and second covered by integration tests for different persistence scenarios which can be produced by your logic.
Entity Framework is tested, but your DAL, especially mapping, is not. I prefer having integration tests to show me that at the very least my mapping is right, and better yet, that I can successfully perform all CRUD operations against my database.
What we usually test DB-wise, is if the complex object graphs can be properly inserted, updated, deleted; basically testing the more complex mappings.
In my opinion there's not really much point in testing if an object with 3 primitive value properties can be inserted and whatnot, because then you'd never see the end of it.
We kind of favor being optimistic (that the simple stuff will just work), we test the more complex associations, and if we encounter an error in our mapping (e.g. an object that should be deleted but isn't) we write an extra test for that.
It's usually not wise to test absolutely everything from a business perspective; you should focus on the high-risk/high-damage stuff first and then work your way down the severity ladder until you think it's not worth it anymore.
1) Have a set of integration tests which test your mappings
2) Make your DAL very light weight but with sufficent power to construct querys, something like:
public interface IDb
{
IQueryable<T>Query<T>();
... (save, delete, get-by-id methods)...
}
3) Write objects which encapsulate the logic behind constructing the query against the DAL
public class MuppetSearch
{
public MuppetColor? Color { get; set;}
public string Name{ get; set; }
public IQueryable<Muppet> ConstructQuery(IDb db)
{
var query = db.Query<Muppet>();
if(Color.HasValue)
{
query = query.Where(m=>m.Value == Color.Value);
}
if(!String.IsNullOrEmpty(Name))
{
query = query.Where(m=>m.Name.Contains(Name));
}
return query;
}
}
4) Test those, mocking all the data you need should be pretty trivial
5) In your service use the search classes to do your query construction

Cannot mock something like TableDomainService where the EntityContext is set in the class definition

I am trying to learn and implement TDD specifically using Moq and I have come up against a design that I can't figure out how to mock:
namespace RIACompletelyRelativeWebService.Web.Services
{
[EnableClientAccess]
public class AncestorDomainService : TableDomainService<AncestorEntityContext>
{
public AncestorDomainService()
{
//this.EntityContext = new AncestorEntityContext();
}
public IQueryable<AncestorEntity> GetAncestorEntities()
{
return this.EntityContext.AncestorEntities;
}
public void AddAncestorEntity(AncestorEntity entity)
{
this.EntityContext.AncestorEntities.Add(entity);
}
}
}
I think I need to mock the TableDomainService so that I can test my AncestorDomainService logic without firing up Azure. I tired something like this:
public class AncestorDomainService<TEntityContext> : TableDomainService<TEntityContext> where TEntityContext is a TableEntityContext
But, the TableDomainService did not like having a generic being used. I also tried setting the EntityContext but it is read only. I have seen other people use the generic DomainService and the Repository design pattern, but since TableDomainService is what lets me use Azure tables behind the scenes, I think I have to stick with TableDomainService<>. Do I just have to fake the TableDomainService, the TableEntityContext and the TableEntitySet that is returned?
I don't know from the code above how the logic you want to test looks like, but you might try seperating your code (the code that you want to test) from the service itself.
You could try to abstract AncestorDomainService (introducing an IAncestorDomainService) and than use moq to mock IAncestorDomainService. Your logic would move to another class that has a dependency to IAncestorDomainService. I've done this with Linq2Sql (which seems to have a similar design and also returns IQueryable). I wouldn't try to mock the 'internals' of TableDomainService because this stuff is usually not designed for easy testing.
THe best solution, if you can afford the time, is to make your code fully testable. That means actually having the scripts necessary to setup an instance of Azure (real or local) with a known good state.
Since the whole point of your AncestorDomainService is to deal with Azure, mocking out its base class doesn't make much sense for a test effectiveness prespective. (Some people choose to optimize for test speed over effectiveness, but I think that's a waste of time.)

Library assembly IoC setup

I am working in a project that has two main parts: a class library assembly and the main application. Both are using Castle Windsor for IoC and both manually setup their list of of components in code (to aid refactoring and prevent the need for a config file). Currently the main application has code like this:
public static void Main()
{
// Perform library IoC setup
LibraryComponent.Init();
// Perform application IoC setup
IoC.Register<IXyz, Abc>("abc");
// etc, etc, ...
// Start the application code ...
}
However the call to initialise the library doesn't seem like a good solution. What is the best way to setup a class library that uses an IoC container to decouple its internal components?
Edit:
Lusid proposed using a static method on each public component in the library that would in turn make the call to initialise. One possible way to make this a bit nicer would be to use something like PostSharp to do this in an aspect-oriented way. However I was hoping for something a bit more elegant ;-)
Lusid also proposed using the AppDomain.AssemblyLoad event to perform custom steps at load time, however I am really after a way to avoid the client assembly from requiring any setup code.
Thanks!
I'm not sure if I'm understanding exactly the problem you are trying to solve, but my first guess is that you are looking for a way to decouple the need to call the Init method from your main application.
One method I've used in the past is a static constructor on a static class in the class library:
static public class LibraryComponent {
static LibraryComponent() {
Init();
}
}
If you have multiple class libraries, and would like a quick and dirty way of evaluating all of them as they are loaded, here's a (kinda hairy) way:
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);
}
static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
IEnumerable<Type> types = args.LoadedAssembly.GetTypes()
.Where(t => typeof(IMyModuleInterface).IsAssignableFrom(t));
foreach (Type t in types)
{
doSomethingWithType(t);
}
}
The Where clause could be anything you want, of course. The code above would find any class deriving from IMyModuleInterface in each assembly that gets loaded into the current AppDomain, and then I can do something with it, whether it be registering dependencies, maintaining an internal list, whatever.
Might not be exactly what you are looking for, but hopefully it helps in some way.
You could have a registration module. Basically LibraryComponent.Init() function takes an IRegistrar to wire everything up.
The IRegistrar could basically have a function Register(Type interface, Type implementation). The implimentor would map that function back to their IOC container.
The downside is that you can't rely on anything specific to the container your using.
Castle Windsor actually has a concept called facilities that are basically just ways of wrapping standardised pieces of configuration. In this model, you would simply add the two facilities to the container and they would do the work.
Of course, this wouldn't really be better than calling a library routine to do the work unless you configured the facilities in a configuration file (consider binsor). If you are really allergic to configuration files, your current solution is probably the best.