writing a test using moq unit testing framework - c#

I'm a bit confused with writing unit tests in C#. I've written the following class for learning Moq. I've noticed the [SetUp] is actually a reference from NUnit. How can I write a test class that only uses one framework or another or whether that's possible? If I want to use Moq what attributes am I missing to successfully run this test? I know there's [TestFixture], [TestMethod] etc.. but which one do I use for Moq!
Thanks,
James
public class CatalogCommandTests
{
private Mock<IReferenceData> _mockReferenceData;
[SetUp]
public void TestInitialize()
{
_mockReferenceData = new Mock<IReferenceData>();
}
public void TestMyGetMethodReturnsListOfStrings()
{
var contractsList = new List<Contract>();
_mockReferenceData.Setup(x => x.MyGetMethod()).Returns(contractsList);
}
}

Your mock looks good. To get the mock of IReferenceData you have to call _mockReferenceData.Object.
A method decorated with the SetUp Attribute will be executed before each test method is called.
(See: Setup).
If you want that TestMyGetMethodReturnsListOfStrings gets called you have to decorate the method with the Test attribute
(See: Test).

Related

Unittests: Create Mock as property in the UnitTest class?

When writing Unittests, I wonder if it is best practice to create a property for the mock like in this example (I am seeing this all over the tutorials in the internet):
public class CartControllerTests
{
private CartController controller;
private Mock<IPaymentService> paymentServiceMock;
[SetUp]
public void Setup()
{
cartServiceMock = new Mock<ICartService>();
}
}
(Taken and adjusted from https://softchris.github.io/pages/dotnet-moq.html#full-code)
Because when I write several Unittests and Setup the mock for a specific behaviour (per test), I think it could be possible, that one setup in the first test could override the second setup in the next test.
Wouldn't it be better to create an own Mock for every Unittest, and just setup it for the specific Test?

Nunit not calling setup once per text fixture

I'm new to Nunit and am trying to run 2 Test Fixtures, A & B. Within each Fixture I have a unique Setup method for each. However, when I click "Run All" in the "Test Explorer" in Visual Studio, the test setup for Fixture A is called (it was executed first) and Setup for Fixture B is ignored. I also get the same behavior when running all tests via command line. Below is my code:
Fixture A
[TestFixture]
public class A
{
[SetUp]
public void SetupTest()
{
// ...Setup for Fixture A
}
[Test, Order(1)]
public void TestForFixtureA()
{
// ...perform test
}
}
Fixture B
[TestFixture]
public class B
{
[SetUp]
public void SetupTest()
{
// ...Setup for Fixture B
}
[Test]
public void TestForFixtureB()
{
// ...perform test
}
}
What is the correct way to get Setup methods to execute per Fixture?
You are using the incorrect attribute for setup at the test fixture level. The attribute you should be using is [SetUpFixture]. Information about this can be found in the nunit documentation
Here is a list of all the setup attributes and their usages taken from the documentation:
SetUpAttribute is now used exclusively for per-test setup.
TearDownAttribute is now used exclusively for per-test teardown.
OneTimeSetUpAttribute is used for one-time setup per test-run. If you
run n tests, this event will only occur once.
OneTimeTearDownAttribute is used for one-time teardown per test-run.
If you run n tests, this event will only occur once
SetUpFixtureAttribute continues to be used as at before, but with
changed method attributes.
This doesn't seem to explain the bizzare behaviour you are seeing, as setup should be ran per-test, but using the correct attributes couldn't hurt.
If you intend your setup to be run once per fixture, use [OneTimeSetUp]. But if you intend it to run once per test within the fixture, then [SetUp] is correct. We can't tell what you intend from the code.
Whichever one you use, the setups should all run. The only situation in which [OneTimeSetUp] will run but [SetUp] will not is when no individual tests are found within the fixture. Are all the tests being recognized?
I suggest you verify very clearly that the setup is not being run. The easiest way is to temporarily create some output from the setup method.

C# AssemblyInitialize not running

I'm trying to do unit testing on my C# ASP.NET project but need to run some initialization code for all tests:
[TestClass()]
public class Init
{
[AssemblyInitialize]
public static void initialize()
{
ContextProvider.setContext(new TestContext());
}
}
That's all I need to run before my tests, but it is not running. I tried to debug all my tests and put a breakpoint in that line but it is not hit. If I comment out the [AssemblyInitialize] and run one particular test that does not require this initialization, it runs successfully. However, with this line in, no tests run (and no breakpoints at all are hit)
What am I missing here?
Phil1970's helpful comment assisted in resolving the issue.
The problem with the initialize method is that it must receive TestContext (Microsoft.VisualStudio.TestTools.UnitTesting.TestContext). I couldn't find any guide/Microsoft documentation that explicitly states this, but the examples in this msdn page do have TestContext as input for the method.
After I added it, the tests ran successfully. On a side note, I had created a class to mock some data I needed and called it TestContext, which turned out to be a very poor name selection and made it more difficult to understand my mistake. I renamed it to APITestContext, here's my fixed initialization class.
[TestClass()]
public class Init
{
[AssemblyInitialize()]
public static void initialize(TestContext testContext)
{
ContextProvider.setContext(new APITestContext());
}
}
Here is (I think) the full list of things to check:
You should be using Microsoft.VisualStudio.TestTools.UnitTesting;
The class must be public
The class CANNOT be static or abstract
The class must be decorated with [TestClass]
The method must be public
The method MUST be static
The method must be decorated with [AssemblyInitialize]
The method must have the signature: void InitName(TestContext tc)
Don't know if it can be related but in the documentation it says
This attribute should not be used on ASP.NET unit tests, that is, any test with [HostType("ASP.NET")] attribute. Because of the stateless nature of IIS and ASP.NET, a method decorated with this attribute might be called more than once per test run.
Are you using that HostType?

Mock inner method using Rhino

I have to do a simple unit test to check if UpdateScript is being called when DateTimeChanged is called. I would like to use mock for UpdateScript because it is a complex legacy code.
I tried using the Mocks and Stubs, but that is not working. Is there a way to mock just the sub method?
public void DateTimeChanged()
{
if (isToggleOn)
{
this.UpdateScript();
}
}

Multiple [SetupTest] for different configs

Is it possible to have multiple [SetupTest]'s in a fixture?
I am using Selenium and nUnit and would like to be able to specify the Browser on which the user wants to test.
I have a simple user GUI for selecting tests to run but, I am aware that in the future we want to hook this up to cruise control to run the tests automatically. Ideally I want tests that can be run on both our GUI and the NUnit GUI.
Is it possible to have multiple [SetupTest]'s in a fixture? No.
It is possible to define all your tests in a base class, have multiple fixtures inherit the tests, and then select an environment dependent fixture type at runtime.
Here’s the stock example that I have for [TestFixtureSetup]. The same principle works for all the setup attributes. Notice that I’m only putting [TestFixture] on the child classes. Since the base “TestClass” doesn’t have complete setup code, you don’t want to run the tests directly.
public class TestClass
{
public virtual void TestFixtureSetUp()
{
// environment independent code...
}
[Test]
public void Test1() { Console.WriteLine("Test1 pass."); }
// More Environment independent tests...
}
[TestFixture]
public class BrowserFixture : TestClass
{
[TestFixtureSetUp]
public override void TestFixtureSetUp()
{
base.TestFixtureSetUp();
// environment dependent code...
}
}
[TestFixture]
public class GUIFixture : TestClass
{
[TestFixtureSetUp]
public override void TestFixtureSetUp()
{
base.TestFixtureSetUp();
// environment dependent code...
}
}
I suspect you can use the parameterized tests introduced in NUnit 2.5 to do what you want, but I'm not totally clear what you want to do here. However, you could define the fixture and have it take a Browser variable in its constructor, then use parameterized TestFixture attributes like
TextFixture["Firefox"]
TestFixture["Chrome"]
public class ParameterizedTestFixture {
//Constructor
public ParameterizedTestFixture( string Browser) {
//set fixture variables relating to browser treatment
}
//rest of class
}
See NUnit Documentation for more info.
The Setup attribute identifies a method that is run before each test. It only makes sense to have one Setup per test fixture - think of it as a 'reset' or 'preparation' before each test is run.

Categories

Resources