How to unit test file permissions in NUnit? - c#

I'm trying to unit test file read operations. In this scenario I also need make sure that, if a particular user don't have read access he should get an exception...
But somehow I'm unable to get it working, can anyone suggest something?
PS: I'm using Rhino mock and NUnit

You could use Rhino.Mocks "Do" extension to throw a specific exception:
public delegate void ThrowExceptionDelegate();
mystub.Stub(x => x.ReadFile()).Do(new ThrowExceptionDelegate(delegate()
{ throw new IOException(); }
));
This would allow you to test your exception handling code.

You need to get a test in place which, in place of reading a file is using a mock that throws an exception instead of really reading a file. Then you can verify that the appropriate handling is triggered and things work out as they should.
If you need a better answer, you need to give an example of your classes and maybe the skeleton of the test you've written so far.

I'd go for a proper acceptance test - using mocks too much can be a bit dangerous. In this case it's easy to programmatically set + unset file permissions anyway.
I had a similar problem - wanted to test a permissions problem + came up with the following helper class to wrap the library API for messing around with file permissions
set file permissions for c:\program files\company\app\file for all users

Related

How do we write unit tests for MIP (Microsoft Information Protection) using C# programming language?

Requirement: If any file has protection(Sensitivity label) then we are throwing an error message.
Before we go and do our actual implementation, I want to achieve this using TDD approach.
Please let me clarify whether the below steps can we achieve using unit test with C#?
Is it possible to write unit test on this MIP? If yes,
Through program , I want to read the file(.pdf or office app files) and apply sensitivity label before using MIP Code.
Once it reaches MIP code snippet ,this should detect this file and it has protection.
If it is protected then should throw an error message or else skip the execution.
I never used the MIP SDK, but you are in the wrong path if you want to test the file information using MIP.
1. Use double testing
First you will have to use Double Testing (a stub or a fake) to be sure that you business rules are applied correctly in your algorithme (throwing the exception if the sensitivity level is bad for example)
The stub or the fake will allow you to control the sensitivity level return, It's also means that you will have to wrap the "MIP Library" inside a class or using IOC
2. Use integration testing
When you will have a first working scenario with you unit test, you will be able to make the same with Integration Testing. You will add to your project the material to have a "production environnement" adding files with differents sentivities to your test project
Conclusion
Of course, I know that my answer is not a working solution but your needs is not simple and cannot be set in a stackoverflow post.
You will need to investigate about double testing & integration testing before making any development if you want to have reliable unit tests.

C# how to log file inside a DLL?

I'm developing a DLL and I want to log some data it generates.
I wanted to use "Log4Net", but I found the problem that in a DLL I don't have an "App.config" file where I can write the XML code, so I don't know how to implement this (I'm new in this matters).
I read about "Singleton" but I saw it's better to avoid it since it has it's issues (i.e hide some visibility of the code, problems with unit tests, ...).
So my question is: How and what is the best way to create a log file for the data generated by my DLL?
A DLL - a class library - should never be logging by itself. Even the ones that are there for output - like the one containing Console or even logger code - should never decide to write their own logfile. Logging work - all output work - that is not controllable or even fully controlled by the programmer using your DLL, is just going to be vexing behavior. And you should never write something with Vexing behavior.
Logging is the job of the person using your code, not of your code. If you are writing a Library or really anything else that usually has no output (like a Windows Service), it is customary to have a wrapper project for debugging and testing.
If it is important enough it warants an Exception. If it is not important enough for a Exception - it is propably not important enough at all. It is a daunting challenge to write good Exception handling, nevermind good Exception throwing code. But there are two articles on the mater that I link very often. And I really think would help you get you on the right paths:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
They really helped me get a handle on it. And thus far they helped countless others. And their ideas are not even tied to .NET only.
The config file will be connected in running module.
It will be in exe file if it's a console application,
or in web.config in case of web application.
To log the application flow in the DLL,
Just create a Class that create and access the log text file.
In that class, declare the object LoggingClass loggingObject; and then use this instance to access the log file.
In creating object for it, you can use,
public static LoggingClass createOrGetObject()
{
return (loggingObject == null)? new LoggingClass() : loggingObject;
}
Now, just you can call this method to get the same instance that access the log file to write the log.
In this example, Log4Net is not used but works fine for logging.
You don't say who you expect to use your dll.
If it will be used by lots of other people and if the logging is useful to them, then may not want to be forced to use log4net or this may cause problems if they want to use a different version of log4net than you are using.
I have seen several dlls which use Common.Logging to avoid this issue which allows the consumers to use whichever logging package they want.
Having said that, see Configure log4net logging in dll for another possible solution.

Specflow / automated testing - making directories inaccessible

So we're using C#/Specflow, and I have a test that reads
Given The publish directory can not be accessed
The app being tested reads/writes files from a directory, firstly checking it exists and if not throws an exception. I am testing that this exception is thrown. What I need to do is make the directory inaccessible for the duration of the test.
The options as I see it are:
Change the directory it's accessing by overriding it's config (Windows registry) for the duration of the test.
Rename the directory it's accessing for the duration of the test.
Change the permissions on the directory for the duration of the test.
None of these seem ideal, I'd like to leave the test server alone if possible. Can anyone tell me of a better solution to this please?
An option that you didn't specify is to mock out the file access behind an interface and then have the mock simulate lack of access.
This has the benefit of not needing to change anything for the test, but means that its not longer an integration tests. If you don't mock and instead change the config/folder access then this test will need to ensure it isn't run when any other tests are running as they might consequently fail due to those changes.
This question has an example of how you might do this simply, and also links this library and this library which might be able to help.

How to run a SpecFlow test through a test harness?

Good afternoon/morning/evening folks,
I was wondering is it possible for me to "execute" a SpecFlow test via some sort of test harness (not NUnit)?
Previously my test harness I built ran MS Unit tests by calling methods from within the DLL that was created when I compiled the tests.
I'm assuming the same is possible in theory since a DLL is created, but im wondering how it will get all of the arguments etc.
So in short, is this possible if so is there a straight forward way to do this or am I barking up the wrong tree?
It's possible, but I'm not clear why you would want to.
Specflow is basically just a clever way of generating tests. Normally these are nUnit tests, but they can also be switched to use mstest. When you save your edits to the .feature file then VS runs a Custom Tool that converts your plaintext into a .feature.cs file that contains a code version of what you wrote with nUnit attributes applied to the methods.
Later, an nUnit runner (nUnit, resharper, gallio, teamcity etc) loads the dll and looks for all public methods marked with [Test] inside public classes marked with [TestFixture]. These methods get called.
There is nothing to stop you writing your own runner, however I'm not sure why you would do that. nUnit provides extensive reporting of the success of your test run in xml format, so its probably faster just to write something to parse that.
So I decided to invest some time on this and figured that using reflection was the way to do this task.
Here is some of my code:
TestRunner.TestDLLString = getDLL(project);
var TestDLL = Assembly.LoadFrom(TestDLLString);
Type myClassType = TestDLL.GetType("SeleniumDPS." + testname);
var instance = Activator.CreateInstance(myClassType);
MethodInfo myInitMethod = myClassType.GetMethod("Initialize");
try
{
myInitMethod.Invoke(instance, null);
}
catch (Exception ex)
{
//Error logging etc
}
I then repeat that for the "[TestMethod]" etc. I understand some people dislike reflection but in this instance the performance isnt critical so it works quite well for us.
So essentially what im doing is reading on the name of the test from an XML file then searching the DLL for that test method, then executing the Intitialize method, and later on executing the test method itself. After the test is run I then execute the cleanup method.
It might seem a bit hacky and NUnit might seem the logical choice for some, but as I mentioned earlier I needed a customizable approach. Thanks for all the suggestions though.

C# Unit Test set HttpRuntime.BinDirectory

I've got a clear and simple question.
The webapplication i'm working on is using unit tests (close to 1500 tests). Due to an required modification in the application several tests are failing because The HttpRuntime.BinDirectory doesn't have a value and therefor throws and ArgumentNullException.
Is there a way to set my own value in HttpRuntime.BinDirectory? Or to Mock it using the Moq framework?
Any help is appreciated!
Assuming your own code is calling into HttpRuntime.BinDirectory, then just don't do that. Create your own class like ExecutionContext with a property BinDirectory which can infer the correct location based on if it's called from asp.net or inside unit tests.
You could also use Assembly.CodeBase instead which will work in both situations as long as you grab one of your own assemblies (not something in the gac).

Categories

Resources