I need to use some WPF components in an NUnit unit test. I run the test through ReSharper, and it fails with the following error when using the WPF object:
System.InvalidOperationException:
The calling thread must be STA, because many UI components require this.
I've read about this problem, and it sounds like the thread needs to be STA, but I haven't figured out how to do this yet. What triggers the problem is the following code:
[Test]
public void MyTest()
{
var textBox = new TextBox();
textBox.Text = "Some text"; // <-- This causes the exception.
}
You should add the RequiresSTA attribut to your test class.
[TestFixture, RequiresSTA]
public class MyTestClass
{
}
With more recent versions, the attribute has changed :
[Apartment(ApartmentState.STA)]
public class MyTestClass
{}
Have you tried this?
... simply create an app.config file for the dll you are attempting to test, and add some NUnit appropriate settings to force NUnit to create the test environemnt as STA instead of MTA.
For convenience sake, here is the config file you would need (or add these sections to your existing config file):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="NUnit">
<section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<NUnit>
<TestRunner>
<add key="ApartmentState" value="STA" />
</TestRunner>
</NUnit>
</configuration>
Related
So I've done some looking around. Most of the threads I find seem related to people wanting to run log4net in their actual tests. Meaning they want log entries in their test class. I don't want log entries from my actual tests. But I do want the expected log entries from the code I am testing. This is my first time using Log4net. If I run the code on it's own, the log entries work. If I run a test, no log entries though. Im guessing it's not initialized properly or perhaps I don't have log4net setup correctly in my UnitTest (in appconfig or assembly maybe??). This is an MVC 5 application. Here is a basic example.
Nunit Test (basics):
namespace MyUnitTests
[TestFixture]
public class MyTestClass
{
[Test]
public void MyTest
{
//arrange
var testVar = #"string";
//act
MyProjectClass.Method(testVar);
//assert something
}
}
so over in MyProject I have (basics):
public class MyProjectClass : Controller
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MyProjectClass));
public static void Method(string myString)
{
//does whatever
log("added value");
}
So I've obviously simplified this for the discussion. But when I run my actual test, my test passes, the values and the outcome are all as they should be. I just never see the log entry in the log for method I just tested. Im sure I'm missing something simple. Any help would be greatly appreciated. Thanks!
If you look in the app.config for your main project, you should see a log4net config section that specifies the location of the log file.
You first need to add log4net to your <configSections> like this:
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
You can then add a <log4net> section to the <configuration> tag. Documentation for this can be found here.
I just want to add the above answer. In addition to setting the appconfig in your UnitTest the same as your Application webconfig (editing the value for log file location if you want) you also need to add the assembly entry as you would have for your application already (changing web.config to app.config in my case).
//logger
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "app.config", Watch = true)]
You'll also need to initialize the logger (at least I did) in your unit test. So basically I added this in my arrange of my test if wanted my logging in the method I was testing to fire. Add something like this in your arrange or setup for you test class possibly:
[Test]
public void MyTest
{
//arrange
log4net.ILog log = log4net.LogManager.GetLogger(typeof(MyTestClass));
log4net.Config.XmlConfigurator.Configure();
}
I have a C# unit test project with application settings in the app.config file. I am testing a class that exists in a different project. That class depends on both, ConfigurationManager.AppSettings and ConfigurationManager.ConnectionStrings.
The project that the class being tested resides in does not have an app.config file. I would have thought that because the class is being instantiated in the context of the unit test project that it would use the unit test project's app.config file. Indeed, that does seem to be the case for the connection string.
The class retrieves the connection string without any issues. However, when the class tries to retrieve any application settings the configuration manager always returns null. What is going on here?
Edit 1
I thought maybe it would be a good idea to try load some settings in the test project to see what happens. I tried to load the setting in the unit test immediately before calling the code that instantiates the class in the external project. Same result, nothing. I guess I can exclude the other project from the equation for the time being.
Here is an excerpt from my config file:
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyNamespace.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
...
<applicationSettings>
<MyNamespace.Properties.Settings>
<setting name="Bing_Key"
serializeAs="String">
<value>...</value>
</setting>
</MyNamespace.Properties.Settings>
</applicationSettings>
and here is how I am attempting to load the setting:
string test = System.Configuration.ConfigurationManager.AppSettings["Bing_Key"];
Consider refactoring your code that accesses the config to use a wrapper. Then you can write mocks for the wrapper class and not have to deal with the importing of the configuration file for the test.
In a library that is common to both, have something like this:
public interface IConfigurationWrapper {
string GetValue(string key);
bool HasKey(string key);
}
Then, in your libraries that need to access config, inject an instance of this interface type into the class that needs to read config.
public class MyClassOne {
private IConfigurationWrapper _configWrapper;
public MyClassOne(IConfigurationWrapper wrapper) {
_configWrapper = wrapper;
} // end constructor
public void MethodThatDependsOnConfiguration() {
string configValue = "";
if(_configWrapper.HasKey("MySetting")) {
configValue = _configWrapper.GetValue("MySetting");
}
} // end method
} // end class MyClassOne
Then, in one of your libraries, create an implementation that depends on the config file.
public class AppConfigWrapper : IConfigurationWrapper {
public string GetValue(string key) {
return ConfigurationManager.AppSettings[key];
}
public bool HasKey(string key) {
return ConfigurationManager.AppSettings.AllKeys.Select((string x) => x.ToUpperInvariant()).Contains(key.ToUpperInvariant());
}
}
Then, in the code that calls your class.
//Some method container
MyClassOne dataClass = new MyClassOne(new AppConfigWrapper());
dataClass.MethodThatDependsOnConfiguration();
Then in your test, you are free from dependency bondage. :) You can either create a fake version that implements IConfigurationWrapper and pass it in for your test, where you hard-code the return values from the GetValue and HasKey functions, or if you're using a mocking library like Moq:
Mock<IConfigurationWrapper> fakeWrapper = new Mock<IConfigurationWrapper>();
fakeWrapper.Setup((x) => x.GetValue(It.IsAny<string>)).Returns("We just bypassed config.");
MyClassOne testObject = new MyClassOne(fakeWrapper.Object);
testObject.MethodThatDependsOnConfiguration();
Here is an article that covers the concept (albeit, for web forms, but the concepts are the same): http://www.schwammysays.net/how-to-unit-test-code-that-uses-appsettings-from-web-config/
You mentioned settings in the project properties. See if you can access the setting this way:
string test = Properties.Settings.Default.Bing_Key;
You may need to get the executing assembly of where the project settings file is defined, but try this first.
EDIT
When using Visual Studio's project settings file, it adds stuff to your app.config and creates the app.config if it is not present. ConfigurationManager CAN'T touch these settings! You can only get to these specific generated project.settings file from using the above static method. If you want to use ConfigurationManager, you will need to hand write your app.config. Add your settings to it like so:
<appSettings>
<add key="bing_api" value="whatever"/>
</appSettings>
If you're using .NET Core your problem could be a known issue caused by the fact that the test process runs as testhost.dll (or testhost.x86.dll), which means the runtime config file is expected to be named "testhost.dll.config" (or "testhost.x86.dll.config"), instead of the app.config output (ex: "MyLibrary.Tests.dll.config").
To fix it, add the code below to your project file (.csproj, etc) inside of root node <Project>. During build, two copies of app.config will be put in the output directory and named "testhost.dll.config" and "testhost.x86.dll.config", which will get your app settings working again. (You only need 1 of these files but it's safer to include both.)
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)\testhost.x86.dll.config" />
</Target>
I recommend app.config only as a temporary solution. If you're like me you might have run into the problem while upgrading a .NET Framework project to .NET Core and needed a quick fix. But don't forget to look into the new, more elegant solutions provided by .NET Core for storing app settings.
And then he screamed "NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO".
Cite: I have a C# unit test project with application settings in the app.config file. I am testing a class that exists in a different project. That class depends on both, ConfigurationManager.AppSettings and ConfigurationManager.ConnectionStrings.
You don't do this. EVER!!!! Why? because you have now created a dependency. Instead, use dependency injection so the class can do its work without having to peak into the configuration file that belongs to the application.
i am first time using any DI framework called unity app block. i am getting error. the error is :-
The type name or alias ILogger could not be resolved. Please check your configuration file and verify this type name.
i was trying inject dependency from out side into my main proj. suppose i want to save data to anywhere by dependency. say suppose i want to save data to file or console, database etc.
here i am telling you how i develop my app for incorporating Unity.
first i create a class library project called "Ilogger" it has only one interface. full code of this interface
namespace Ilogger
{
public interface ILog
{
void Write(string msg);
}
}
secondly i create a class library project called "ConsoleWriter" it has only one class which inherit Ilogger interface.so i just add the reference of Ilogger project into ConsoleWriter proj. full code of this ConsoleWriter
namespace ConsoleWriter
{
public class ConsoleWriter : Ilogger.ILog
{
#region ILog Members
public void Write(string msg)
{
Console.WriteLine(msg);
Console.ReadLine();
}
#endregion
}
}
3rd step i create a class library project called "FileWriter
" it has only one class which inherit Ilogger interface.so i just add the reference of Ilogger project into FileWriter proj. full code of this FileWriter
namespace FileWriter
{
public class FileWriter : Ilogger.ILog
{
#region IWriter Members
public void Write(string msg)
{
using (StreamWriter streamWriter = new StreamWriter("c:\\TestUnity.txt", true))
{
streamWriter.WriteLine(msg);
}
}
#endregion
}
}
next i create my win apps from where i inject dependecy at runtime. in this project i add some dll reference of unity block and those are.
Microsoft.Practices.Unity
Microsoft.Practices.Unity.Configuration
system.configuration
i add one app.config file and it has entry like
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias type="ILogger.ILog, ILogger" alias="ILogger" />
<namespace name="ILogger.ILog"/>
<container>
<register mapTo="FileWriter.FileWriter, FileWriter" name="MyFileWriter" type="ILogger"/>
<register mapTo="ConsoleWriter.ConsoleWriter, ConsoleWriter" name="MyConsoleWriter" type="ILogger"/>
</container>
</unity>
</configuration>
here is the main code from where error is thrown
string strCountryCode = "USA";
IDictionary<string, string> loggers = new Dictionary<string, string>();
loggers.Add("USA", "MyFileWriter");
loggers.Add("GBR", "MyConsoleWriter");
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)System.Configuration.ConfigurationManager.GetSection("unity");
//container.LoadConfiguration();
section.Containers.Default.Configure(container);
Ilogger.ILog logger = container.Resolve<Ilogger.ILog>(loggers[strCountryCode]);
logger.Write("Hello World");
this line giving error section.Containers.Default.Configure(container);
i am using DI framework unity first time so i am not being able to catch what mistake i made. so please anyone help me to get the error and tell me how to fix it.
thanks
there may be several issues;
in the entry point of application, where you are trying to read unity configuration, you need to add the assembly which contains ILog interface; the assembly may be missing.
you need to add aliases using full paths; the full path needs to include the assembly name.
in order to observe exact problem, instead of using a configuration file, try to make registrations in the code.
in code i can do some thing like this:
container.Register(AllTypes.FromAssemblyNamed("AssemblyName"));
can i do the same thing using Configuration file "Windsor.Config"???
Responding to your comment.
There's also a 3rd way (in Windsor 2.5, currently in beta 2 - final release is expected very soon).
You can have each of your modules reference Windsor, and each module have its own set of Installers.
Than you can use the new directory scanning capability to install components from all these assemblies:
// In your root assembly
var container = new WindsorContainer();
container.Install(
FromAssembly.This(),
FromAssembly.InDirectory(new AssemblyFilter("Modules")),
Configuration.FromAppConfig()
)
In addition if you have components following identical structure you can also register components from multiple assemblies in single installer. See more here.
container.Register(
AllTypes.FromAssemblyInDirectory(new AssemblyFilter("Modules"))
.Where(t=>t.Namespace.EndsWith(".Services"))
.WithService.DefaultInterface()
);
I am pretty sure that only with the fluent configuration API can you set up conventions for your application so that as you create new components you aren’t required to register them individually, as you example shows.
You can write a trivial facility to do that, e.g.:
AllTypesConfig.xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<facilities>
<facility id="alltypes">
<assemblies>
<item>Castle.Core</item>
</assemblies>
</facility>
</facilities>
</configuration>
code:
public class AllTypesFacility : AbstractFacility {
protected override void Init() {
var asmList = FacilityConfig.Children["assemblies"].Children;
foreach (var asm in asmList)
Kernel.Register(AllTypes.FromAssemblyNamed(asm.Value).Pick());
}
}
var container = new WindsorContainer(#"..\..\AllTypesConfig.xml");
container.AddFacility("alltypes", new AllTypesFacility());
container.Resolve<NullLogger>();
If you need more flexibility it will get progressively harder to represent the fluent config in XML.
Even though the solution is so obvious I should have never have posted this, I'm leaving it up as a reminder and a useful point of reference to others.
I've got the following in my app.config file:
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
Followed by:
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<object name="mediaLibrary" type="AlbumLibraryWPF.AlbumLibrary, AlbumLibraryWPF"/>
</objects>
</spring>
Then in my app I've got:
using Spring.Context;
using Spring.Context.Support;
public partial class AlbumChecker : Window
{
private DataTable dataTable;
private Library library;
private Thread libraryThread;
public AlbumChecker()
{
InitializeComponent();
CreateToolTips();
IApplicationContext ctx = ContextRegistry.GetContext();
library = (Library)ctx.GetObject("mediaLibrary");
// Other initialisation
}
// Other code
}
It all compiles quite nicely, however, I'm getting an exception raised on the call to GetContext():
Error creating context 'spring.root': Could not load type from string value
'AlbumLibraryWPF.AlbumLibrary, AlbumLibraryWPF'.
I've checked the Spring.NET documentation and can't see what I'm doing wrong - but I clearly have got something wrong, otherwise it wouldn't raise the exception!
AlbumLibraryWPF is the namespace and AlbumLibraryWPF.AlbumLibrary is the fully qualified name of the class I want to instantiate. I'm guessing that it's this I've got wrong, but can't see how.
I feel such a fool.
It was because I'd failed to copy the AlbumLibrary.dll to the correct output directory. That meant that Spring couldn't find it - even after I'd fixed the assembly name problem Kent highlighted.
The name after the comma should be the assembly name, which is not necessarily the same as the namespace name.
I was getting this error because by mistake there was a typo [!*2] in app.config file. Once I took that out , error went away. some thing like this
<context>
<!--<resource uri="~//Aspects.xml"/>-->
<!--<resource uri="~//Dao.xml"/>-->
<!--<resource uri="~//Spring.xml"/>-->
<resource uri="file://Spring.xml"/>
<resource uri="file://Dao.xml"/>
</context>
!*2
You should use tha id attribute instead of name:
<object id="mediaLibrary" type="AlbumLibraryWPF.AlbumLibrary, AlbumLibraryWPF"/>
Also it should be config://spring/objects instead of config://spring/obects.
You need to double check that you have a type called AlbumLibrary in AlbumLibraryWPF namespace defined in AlbumLibraryWPF assembly.
You can try change the type. The type="AlbumLibraryWPF.AlbumLibrary, AlbumLibraryWPF", first parameter means NameSpace and the second parameter (behind the dot) means Solution Name.
"AlbumLibraryWPF.AlbumLibrary" = NameSapce name
"AlbumLibraryWPF" = solution name
Open VS2012 or VS2010 with Administrator Permissions
Config: type="namespace.type, assembly"
Then try running your solution again.