Why does unit test fail on first run? - c#

I have 7 unit tests which fail when I run all tests from Solution level or from the test runner, but, when I run the tests from project level or from the project within the test runner they succeed.
I am trying to test that I can resolve an item from a Castle Windsor container once they have been installed.
[TestFixture]
public class Having_installed_the_request_processors
{
private IWindsorContainer _container;
[SetUp]
public void Setup()
{
_container = new WindsorContainer();
_container.Install(FromAssembly.Containing<RequestProcessorInstaller>());
}
[TearDown]
public void Teardown()
{
((WindsorContainer)this._container).Dispose();
_container = null;
}
[Test]
public void can_resolve_the_job_status_request_processor()
{
Assert.That(_container.Resolve<IJobStatusRequestProcessor>(), Is.Not.Null);
}
}
This is the error returned:
SetUp : Castle.MicroKernel.SubSystems.Conversion.ConverterException : Could not convert string 'Castle.Services.Logging.Log4netIntegration.Log4netFactory,Castle.Services.Logging.Log4netIntegration,Version=3.3.0.0, Culture=neutral,PublicKeyToken=407dd0808d44fbdc' to a type. Assembly was not found. Make sure it was deployed and the name was not mistyped.
As far as I can see the code in my test project is the same as my production code (which appears to function as expected).
Do you see any issues with the above?
Why does the test succeed in the aforementioned way?

I determined that this was due to the way in which the projects in the solution referenced each other, by changing the direction of some references it resolved the issue - thank you for looking

Related

NUnit TestFixtures do not work with RestSharp

I'm trying to use NUnit TestAttributes to create and delete a RestSharp RestClient
https://github.com/nunit/docs/wiki/TestFixture-Attribute
using NUnit.Framework;
using RestSharp;
namespace Sanitized.Sanitized.Steps
{
[TestFixture]
public class SetupAndTeardown
{
public RestClient restClient;
[SetUp]
public void Init()
{
restClient = new RestClient();
}
[TearDown]
public void Cleanup()
{
restClient = null;
}
}
}
But, I get the error Object reference not set to an instance of an object. when trying to use this in another class i.e. with my automated steps.
I don't understand this, as I thought code that's in the [SetUp] [Teardown] attributes are called at the beginning and end of the test respectively.
You created a TestFixture, which is a class that contains tests. If the fixture had any tests, then NUnit would run them and would also run the setup before each test and the teardown after each test. Since you have no tests, that isn't happening. NUnit recognizes the fixture but finds nothing to run there.
You say that you have a problem when you "use" this fixture in another class. Test fixtures are not intended to be "used" by other code. Rather, they are run by NUnit.
For a better answer about how to do what you are trying to do, we first need to know what you are trying to do. When do you want the "setup" and "teardown" to run? How often should they run? Depending on those things, I can update this answer.
Replying further to your comment... If your tests are in another class, then that class is your test fixture. Is there a reason you don't want it to be the fixture?

Lightinject and xUnit InjectData

I'm trying to setup xUnit with the LightInject framework but cannot get the xUnit InlineDataAttribute to work. The following test code doesn't work:
public static void Configure(IServiceContainer container)
{
container.Register<FooController>();
}
[Theory, InjectData, InlineData("data")]
public void Test_GetViolations_Should_Return_A_Non_Empty_List(FooController service, string somedata)
{
Assert.NotEmpty(service.GetViolations(somedata));
}
This gives an error saying that it cannot find anything to inject for the parameter somedata. Removing the InlineDataAttribute will make the injection work. I really like the InlineData feature of xUnit so how do I get it to work with LightInject?
This has been fixed by the LightInject author. Now it's possible to do this.

NUnit in vs2012 reusing app.config when i click "Run All Tests" on multiple project solution?

I have a visual studio 2012 solution with 2 projects projA and projB, and 2 test projects projA_test and projB_test (using NUnit). ProjA and ProjB both have their own app.config with their own appsettings key/value pairs. When I click the run all tests the projA unit-tests are ran followed by the projB unit-tests. But some of the projB unit tests are failing because of ConfigurationManager.AppSettings has only the values from the app.config from projA! Is this normal behaviour or do I have some configuration setting messed up?
Edit.
A point I forgot to mention is that TeamCity (our CI server) does not fail the tests. So my local unit-test runner seems to be doing something weird..
For each of your unit tests you can just set the values for the ConfigurationManager as such.
ConfigurationManager.AppSettings["YourKey"] = YourValue;
If you do this before you objects that require those values they will work just fine. If they values are for multiple test you can do it in the testfixture setup method.
Detailed Example
Class:
public class SomeClass
{
#region Properties
public string Value { get; private set; }
#endregion Properites
#region Constructors
public SomeClass()
{
Value = ConfigurationManager.AppSettings["DatValue"];
}
#endregion Constructors
}
Test: I know this is MSTest/FluentAssertion but concept should work the same
[TestMethod]
public void Example()
{
#region Arrange
ConfigurationManager.AppSettings["DatValue"] = "Batman";
#endregion Arrange
#region Act
var someClass = new SomeClass();
#endregion Act
#region Assert
someClass.Should().NotBeNull();
someClass.Should().BeOfType<SomeClass>();
someClass.Value.Should().BeEquivalentTo("Batman");
#endregion Assert
}
This test passes in the example I just made and has no app.config file available. A unit test shouldn't be dependent on an app.config otherwise you start creepying from unit test to integration testing.
A note that ConnectionStrings are a little different. You would add those to the ConfigurationManager as such:
ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings("Name", "ConnectionString"));

Moq - how to initialize testing object once for multiple tests

I am trying to structure my unit test in such a way that if I change the constructor of the object being tested I don't have to change a lot of tests. Here is a simplified example of my set up right now:
[TestMethod]
public void Test1()
{
_mockedObject1.Setup(etc);
_mockedObject2.Setup(etc);
var service = new TestedService(_mockedObject1.Object, _mockedObject2.Object, ...,
_mockedObject7.Object);
//Act and Assert
}
Now I've got 20 unit tests that are arranged this same way. If I have to change the constructor of TestedService I have to go into all 20 tests and change the line that creates service. Can I pull this line of code out into TestInitialize or something so that I would only have to change it one time? My first thought is that I can't because then service would get created before my .Setups. Is there another way to handle this?
Yes, you can pull the creation of your service before setting up the dependencies. The SetUp will still be bound to the mocked objects. You could try something like:
private TestedService service;
[SetUp]
public void SetUp()
{
this.service = new TestedService(_mockedObject1.Object, _mockedObject2.Object, ...,
_mockedObject7.Object);
}
[TestMethod]
public void Test1()
{
_mockedObject1.Setup(etc);
_mockedObject2.Setup(etc);
//Act and Assert
this.service.Whatever(...);
}
Take a look at Automoqing since you are already using Moq it would do what you want or even better. Simply it is Dependency Injection container that injects mocks.
You can initialize these objects in the function with a [ClassInitialize()] attribute. This is supposed to run before any tests within that class run.

Unit Test with Ninject Instantiate

I'm trying to test my service using ninject and an unit test project with visual studio 2012. My inject works ok on my controllers, but when I try to do the same in the unit test class I get an Exception.
System.NullReferenceException: Object reference not set to an instance of an object.
namespace Trex.UnitTests
{
[TestClass]
public class GiftServiceTests
{
private IGiftService _giftService;
public void GiftServiceTest(IGiftService giftService)
{
_giftService = giftService;
}
[TestMethod]
public void AddGift()
{
var list = _gift.FindAll(); <--- this line throw an exception
}
}
}
I think there is something wrong with the injection but I dont get it.
It looks to me like a typo of _giftService. In addition, attribute [TestInitialize] needs to be used in your constructor.
Try the following code by placing the correct service name _giftService - that your code is injecting instead:
var list = __giftService.FindAll();
Edit: Unit testing should be done without Ninject. Just create an instance of the object under test and inject a mock for every dependency manually.
Here is a sample with [TestInitialize]:
The unit test must have a default constructor:
[TestClass]
public class TestControllersHomeController
{
private HomeController _sut;
[TestInitialize]
public void MyTestInitialize()
{
var kernel = NinjectWebCommon.CreatePublicKernel();
_sut = kernel.Resolve<HomeController>();
}
[TestMethod]
public void TestIndex()
{
var result = _sut.Index();
Assert.IsNotNull(result);
}
}
The only way dependency injection is able to call your constructor and fill it with a parameter that has a value is if the dependency injection kernel is the one that instantiates your class.
In your case, MSTest is instantiating your test class, so Ninject does not have a chance to call your constructor.
To be honest, you are going about this the wrong way. You will battle MSTest if you pursue this further to try to get Ninject (or any other DI framework) to instantiate your test classes.
I would recommend you use 'new' to instantiate the class under test (_giftService = new GiftService();). If that class has dependencies in its constructor, use a mocking framework to pass in mocked version of those dependencies. This way you isolate your unit tests to only the functionality of the class under test.
_gift is null. Your variable is _giftService. You also should use the [TestInitialize] attribute for your constructor.
Extra tip:
You shouldn't create any dependencies in your unit test. So the giftService which you want to use should be a mock or a stub.

Categories