NUnit: How to start a test only with one userRole, while there are 3 different userRoles defined in TestFixture - nunit

I have a "Regression Test" Class in which i defined 3 different user Roles in the TestFixture
In the regression test i'm testing other web app functionalities beside of the main feature functionalities. Currently im having there 5 different tests as seen below in the screenshot.
What i want now is, that the first 4 Test Methods will be started ONLY with the admin user Role, and the last Test Method called UserRights should be tested only with hsuINT and hsuIntRequest
The problem im having right now is, that all the 5 Test Methods will be started with all userRoles defined at the class in TestFixture
Is there a way, how to tell the TestMethod with which UserRole it should start the test?

In NUnit, the primary purpose of a TestFixture is to group together all the tests that need a common setup. So if the first four tests require the user role admin, and the last one requires running under two different roles, they don't belong in the same TestFixture.
You can restructure your tests into two fixtures, similar to this:
[TestFixture("adminInt")]
public class FirstFixture
{
// Your first four tests here
}
[TestFixture("hsuINT")]
[TestFixture("hsuIntRequest")]
public class SecondFixture
{
// Your last test here
}
Of course, the first fixture doesn't really need a parameter... you can hard code the role if you prefer.
If splitting the fixture requires duplicating a lot of setup code (which you don't show in the question) you can derive each class from a common base, which has the setup. In that case, all three classes should have the parameter but only the two derived classes should have the TestFixture attribute.

Related

How is state shared between nunit tests?

There are some configuration settings that most of the tests in an integration test suite will need to share. These include database connection strings and similar items. It's very slow to fetch these from the system where they are stored. I'm planning to create a Fixture class with the SetUpFixture attribute that's in the root namespace of the assembly and use the OneTimeSetup attribute for the method that gets the config data. That will ensure it only runs one time before any of the tests start.
I can use a static property on the same Fixture class and then individual tests can read the config items with Fixture.ConfigSettings. This seems to work fine in some preliminary testing. Since the tests only read these settings there shouldn't be any cross test interference.
Is an arrangement like this a common way to handle this situation with NUnit? Are there other built in NUnit features or recommended pattern that may be helpful?
Yes, this will work. You should be clear, however that a SetUpFixture and a TestFixture serve different purposes. Do not use both attributes on the same class. Do not inherit one from the other.
As you noted, only static properties will work in this situation and the values should not change once set.

How to execute seed step using migration.exe on existing database?

I have someone else's ASP.NET application that uses code-first EF and comes with the code for database migration and seed. I usually run migration.exe before the new version of the app gets installed and it worked well as long as I let EF do everything starting from creating a brand new database. Now I have to make it work against an existing and EMPTY database. When I run migration.exe it doesn't return any errors and perform all the required migration steps but it not longer runs seed step (it probably assumes it's not needed since the database already exists). How do I force running seed step in this case?
There are steps you need to ensure are set for your database initialization to achieve what you want:
CreateDatabaseIfNotExists: This is default initializer. As the name suggests, it will create the database if none exists as per the configuration. However, if you change the model class and then run the application with this initializer, then it will throw an exception.
DropCreateDatabaseIfModelChanges: This initializer drops an existing database and creates a new database, if your model classes (entity classes) have been changed. So you don't have to worry about maintaining your database schema, when your model classes change.
DropCreateDatabaseAlways: As the name suggests, this initializer drops an existing database every time you run the application, irrespective of whether your model classes have changed or not. This will be useful, when you want fresh database, every time you run the application, like while you are developing the application.
Custom DB Initializer: You can also create your own custom initializer, if any of the above doesn't satisfy your requirements or you want to do some other process that initializes the database using the above initializer.
The best help guide I followed with getting started on understanding Code first was written here and references the part you are referring to:
http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx
The important thing though is to know that you may want different things for different environments too and may wish to get into understanding how to do different deployments for different environments.
An example of a custom one would be like this:
public class EasyContext : DbContext
{
public EasyContext() : base("name=EasyEntity")
{
Database.SetInitializer<EasyContext>(new EasyInitializer());
}
public DbSet<Person> Person { get; set; }
}
You should be setting a breakpoint to make sure it is being caught or else you can force a new configuration to fire as well.

How to unit test an entity is targeting the correct DBMS table

I have the following entity and it was not until run time that i realized that the table name annotation is incorrect.
How can i write unit tests to prevent this?
#Entity
#Table(name = "cache_server")
public class VirtualMachine implements Serializable {
}
It is not about unit testing here, but rather about integration testing, as you need a JPA provider to test it (with a DB server). And when it comes to integration tests, it is very specific to what technologies you use. If you are in Application Server, like Jboss, take a look at Arquillian.
UPDATE
Although I think that usually you do not want to unit test values in annotations, as they represent configuration data, you can always read the values in the annotations using some reflexion. See this question (directly in the question) for an example.

ASP.Net MVC2 Validate two ViewModels of the same class differently using DataAnnotations

I'm using DataAnnotations for validation of a custom class (LINQ to SQL auto generated) using the MetadataType tag on top of the class. I'm loving DataAnnotations and it works well in simple, common scenarios. E.g.
[MetadataType(typeof(Person_Validation))]
public class Person
But what if you need to have two different sets of validation rules applied to the class in different scenarios???
My situation: Some fields are mandatory on the www public-facing site, but not mandatory on the internal admin site. But both sites have a View which "Creates New" of the same object/class.
This is where it becomes DataAnnotations HELL surfaces..
I've tried using two different ViewModels with different validation applied to each of them, two classes that inherit from Person with different validation applied to each of them. But all roads seem to conflict with DRY principals and you end up somewhere along the line having the totally respecify all properties for the underlying class structure. You don't have to do this when you just have one validation rule set. So it very quickly becomes hell and not practical for complex objects.
Is this possible using DataAnnotations and what is the best DRY architecture?
Not sure what you mean by 'virtually duplicate and manually set each and every property manually in the original underlying class'. I've never liked the idea of buddy classes, and would personally recommend different view models for Admin and Public site (with appropriate validation set on each), and then mapping between the models using AutoMapper.
UPDATE:
Regading Automapper, the basic usage is something like this:
First you have to define your mappings. This lets automapper figure out in advance how to map objects. You only need to do this once in the application, so a good place to do this in an ASP.NET app is in Application_Start() in Global.asax. For each pair of classes you want to map between, call: Mapper.CreateMap<SourceType, DestinationType>();
Then, in your application code to do the map you just use:
var destinationObject = Mapper.Map<SourceType, DestinationType>(sourceOjbect);

ObjectContext never derives from an interface?? How do you apply DI/IoC in case of multiple types of ObjectContext?

If you have a system that has multiple types of object contexts. For Eg: BillingObjectContext, HumanResourceObjectContext etc. All derive from ObjectContext but ObjectContext Class does not implement any specific interface like IObjectContext. How would you apply DI/IoC in case of multiple types of ObjectContext say using Ninject?
If you must depend on it in a test, you have to mock it. Here's a sample; it's not much harder than implementing an interface. See also TDD improvements in EF 4.
Why can't we just create the actual context object to be used in our tests? Since we don't want our tests to affect the production database, we can always specify a connection string that points to a test database. Before running each test, construct a new context, add the data you will need in your test, proceed with the unit test, then in the test cleanup section, delete all the records that were created during the test. The only side-affect here would be that the auto-increment IDs would be used up in the test database, but since it's a test database - who cares?
I know that most answers regarding this question propose using DI/IoC designs to create interfaces for data contexts etc. but the reason I am using Entity Framework is exactly to not write any interfaces for my database connections, object models, and simple CRUD transactions. To write mock interfaces for my data objects and to write complex queryable objects to support LINQ, defeats the purpose of relying on highly-tested and reliable Entity Framework.
This pattern for unit testing is not new - Ruby on Rails has been using it for a long time and it's worked out great. Just as .NET provides EF, RoR provides ActiveRecord objects and each unit test creates the objects it needs, proceeds with the tests, and then deletes all the constructed records.
How to specify connection string for test environment? Since all tests are in their own dedicated test project, adding a new App.Config file with a connection string for the test database would suffice.
Just think of how much headache and pain this will save you.
namespace ProjectNamespace
{
[TestClass]
public class UnitTest1
{
private ObjectContext objContext;
[TestInitialize]
public void SetUp()
{
// Create the object context and add all the necessary data records.
}
[TestMethod]
public void TestMethod1()
{
// Runs the tests.
}
[TestCleanup]
public void CleanUp()
{
// Delete created records.
}
}
}