How to properly initialize EF7 for xunit tests run with xunit.runner.dnx - xunit

I have a DNX unit test assembly where I'm testing code that uses EF7.
In a web app, I have the Startup class where I can provide a ConfigureServices(IServiceCollection services) method and initialize like so:
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<RadarDbContext>(options =>
options.UseSqlServer(
Configuration["Data:DefaultConnection:ConnectionString"]));
}
Where is the equivalent "hook" for an xunit test running under DNX?

The DNX runner for Xunit never calls Startup.cs. The "hook" you are looking for is either a class fixture or your test class constructor. (See https://xunit.github.io/docs/shared-context.html)
How you choose to initialize EF from there is up to you. You could use dependency injection and follow the .AddDbContext() pattern above or you could initialize your DbContext directly. (see https://github.com/aspnet/EntityFramework/wiki/Configuring-a-DbContext which is slightly outdated)

Related

Launch spring boot mvc test from custom testng framework

Where I'm working one of our customer required to use a custom test framework written using testng that allows to handle different parameters and test iterations using excel files.
This framework uses a main class to handle all the tests, lets call it TestManager.
This TestManager defines all the #Before and #After operations and has a method called exec() which is annotated as #Test.
This method is used to call the different components required from the test, these components are java classes that implements a single method exec() containing the logic of the single component.
public class TestManager {
// ... Before, After methods
#Test(
dataProvider = "..."
)
public void exec(Parameter[] inParameter) {
// load parameters...
foreach component:
component.exec()
}
}
public class ComponentXYZ {
public void exec() {
// load input params
// Call a microservice and get results, find value on db, selenium operations...
// unload output params for next components
}
}
This framework was designed to be used with selenium, or to test microservices using some http request library and is contained in a standalone module.
So my project has:
A spring boot module
A test module which (in my idea) should have a dependency over the spring boot module
Given this situation do you think it could be possible to use WebMvcTest to perform integration tests while using this custom framework?
I've been trying for a while but I'm always getting errors or I'm not able to #Autowire MockMvc, I can't seem to start a minimal spring boot instance directly from this test framework...
I don't think running my spring boot app and calling the microservices using http is the correct way to test but at this moment is the only thing it's working.

Exception thrown when accessing DBContext from unit test

Any unit test the includes a call to SELECT (using LINQ) data from my DBContext throws the following error:
The model backing the 'MyDBContext' context has changed since the
database was created. Either manually delete/update the database, or
call Database.SetInitializer with an IDatabaseInitializer instance.
For example, the DropCreateDatabaseIfModelChanges strategy will
automatically delete and recreate the database, and optionally seed it
with new data.
Doing a search for that specific error leads me to believe that I need to include the following line in my Global.asax Application_Start method:
System.Data.Entity.Database.SetInitializer<MyDBContext>( null );
This is suppose to fix a similar error when running the application itself. Unfortunately, I don't get this error when I run my application and there doesn't seem to be an Application_Start method for my unit test project. Is there any way to to the unit test project that I'm using a custom database back-end and to ignore any changes that have occurred in it?
I added the unit test project after working on my main project for a while so it's possible I messed it up somehow, but I can't figure out for the life of me what to do. I'm using the built in unit testing in Visual Studio 2010.
There are 2 methods that you could use with the VS unit testing framework allowing you to run some code before and after each test and before and after all the tests contained in the file
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
}
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
}
or:
// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
}
// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup()
{
}

Unit Testing While Using Entity Framework

I have a web application that has been created using MVC 3 and Entity Framework. I would like to start using unit testing, but so far I have not been able to run any unit tests due to the way the system talks to the database.
I have a BaseController, which defines a DataContext as a variable:
public class BaseController : Controller
{
public Models.MyEntities DataContext = new Models.MyEntities();
Each controller then inherits the BaseController, thereby making the DataContext variable available to all controllers without redefining it:
public class ErrorController : BaseController
{
When I run a unit test, I receive an error about the object reference not being set to an instance of an object, each time referring to the line where I access DataContext.
Most references to unit testing say you should be abstracting your database layer, and using fake data for testing. This seems counter-intuitive to me, but that is a different discussion.
My question is - is it possible to use unit testing with the system configured the way it is? I am open to using any testing framework available, either MSTest, NUnit / XUnit etc.

Testing If a class is being activated using WebActivator and if add a IModelBinder to ModelBinderProviders.BinderProviders.

Dear fellows from Stack Exchange.
I'm trying to test if my Custom Model Binder is being added to the ModelBinderProviders.BinderProviders collection.
I decided to activate this through WebActivator, to avoid messing global.asax,
Everything works fine, but the Test:
I tried using the WebActivator.ActivationManager.Run() method, but my things weren't loaded.
I've something like this in my test:
[TestMethod]
public void TemplateModelBinderProvider_Should_Be_Registered_In_BinderProviders()
{
WebActivator.ActivationManager.Run();
IModelBinderProvider templateModelBinderProvider = ModelBinderProviders.BinderProviders.
Where(x => x is TemplateModelBinderProvider).
FirstOrDefault();
Assert.IsNotNull(templateModelBinderProvider);
}
And this is my app_Start class:
[assembly: WebActivator.PreApplicationStartMethod(typeof(MVC.App_Start.MVCBindings), "Start")]
namespace MVC.App_Start
{
public static class MVCBindings
{
public static void Start()
{
ModelBinderProviders.BinderProviders.Add(new TemplateModelBinderProvider());
}
}
}
Sorry you have problems with the piece of code I wrote.
I don't have access to the source code right now but will take a look in the evening (UK time).
Do you think you could send me your solution so I could replicate it locally? My email is jkonecki at gmail.com
UPDATE
I have received your source code but unfortunately it contains references to libraries I cannot obtain so I cannot compile it.
I have created a separate solution (emailed to you) with MVC3 web app and unit test projects that uses your custom model binder provide. There are two tests that prove that WebActivatorManager.Run method properly registers a custom provider.
Try debugging your unit test to make sure that Run method calls your static Start method.
WebActivator source code is here - you might want to get it and step through.

Integration testing against an http server - junit?

I want to to integration tests against an http server. So far I have only experiences with junit for unit testing.
I have two requirements: The framework must have a maven plugin and the tests cases code must be clean - so no dirty hacks and no boilerplate code.
Plain JUnit is good for unit testings, #Test methods are individual. But for integration testing I have to process several dependant steps which must exchange some kind of state (variables).
I already read:
Can we use JUNIT for Automated Integration Testing? and Passing JUnit data between tests and came to the conclusion that I don't like static fields in unit test and I don't want to use TestNG and add dependency annotations on tests and I don't want to put my test into one long unreadable test method.
I though more about some syntax like:
public class MyIntegrationTest() {
#Step
public void testCreate(Context context) {context.put("foo");}
#Step
public void testUpdate(Context context) {context.get();}
#Step
public void testDelete(Context context) {context.get()}
}
So I want to enhance/use ?Unit in a way that it executes #Step methods with a context instance as argument. The methods must be called by the framework in order and cannot be called individually. In a perfect world, all ?Unit guis would show the #Step like an #Test but this is optional...
Any hints how to do this?
Jan
The first point is to check the Maven Failsafe Plugin which is intended for doing integration tests with Maven. Second you have to name your Integration tests based on the conventions used by Maven FailSafe Plugin after that you should be able to run your integration tests simply with maven (by mvn clean verify).
So this means you have to name your integration test like MyIntegrationIT.java...To define the order of executions you have to use a different framework than JUnit may be TestNG which supports this kind of needs, but you already excluded it. So the questions is what kind of tests would you like to do? Page-flows etc. may be a look at JWebUnit might be look worth...
You might also want to consider http://httpunit.sourceforge.net/. It's useful for checking to see if responses come back from the http server.
However, it doesn't do the #Step functionality. Normally I'd do that by :
#Test
public void MasterTest() {
step1(..);
step2(..);
....
}
public void step1(...){...}
public void step2(...){...}

Resources