Rider NUnit Test problem: Program does not contain main - c#

I can't start my NUnit testing on Rider (JetBrains). I have a Console Application project named ISDI and I'm tryin to Test it with a NUnit testing project named ISDITest in the same solution.
This is my code:
using System;
using ISDI;
using NUnit.Framework;
namespace ISDITest {
[TestFixture]
public class TestNome
{
[Test]
public void TestRoom()
{
IRoom r = new Room(0);
IEntity p = new Player();
r.InsertEntity(p);
Assert.Equals(r.GetEntities().Count, 1);
Assert.True(r.GetEntities().Contains(p));
}
}
}
When I try to run the test I get a build error:
Program does not contain a static 'Main' method suitable for an entry point
I think testing methods in a testing class would not need a Main and I don't know how to solve this as I already specified that this is a Testing project when I created it.
I'm sorry if this is a stupid question but I'm just getting started with C# and testing.

Solved this putting an empty Main in the project I wanted to test. Still, it does not make any sense to me.

When running a program, you need an entry point - a place for the code to start. Usually, Main is used for this, but when you have NUnit, you can use a [Test] as an entry point.
When you want to run tests, you need to use the [Test] flag as the point of entry for the program. You do not need a Main method for this.
I recommend reading the Rider / Unit Testing documentation for more information on how to run your [Test] code without implementing a Main method.
https://www.jetbrains.com/help/rider/Unit_Testing__Index.html

Related

How to write test cases for a Program.cs code, without main method or no any method inside?

I am using .Net 6.0
I have a file in my project : Program.cs, containing registration and mapping code for controllers and services.
like:
builder.Services.AddControllers();
builder.Services.AddServices();
Now, I want to write, test cases for these lines of code, but there is no any method to call from the [Fact] method, inside the program.cs. Not even the main() method.
Can somebody please put some light on how can we cover this code with our test cases ?
When you create a new web application in VS2022, there's a checkbox "Do not use top-level statements". If you leave it unchecked, you get what you're seeing in Program.cs. If you do check it, you'll get:
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
/* Everything exactly as you see in your Program.cs, but indented */
}
}
}
So if you do envisage wanting to call this method in tests (slightly odd, but okay), I'd recommend using this option rather than creating a separate method to call from Program.cs.
Even if you do get that checkbox option wrong during project creation, you should hopefully see that it's not tricky to transform between the two forms, using the above as a template (and adjusting namespace name)
Followed below steps to complete my code coverage:
Created an extension method for WebApplicationBuilder within a new static class.
Moved the testable code from Program.cs to the extension method.
Wrote the test cases for the extension 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?

Prevent NUnit tests to run depending on environment

I'm struggle with this one quite a long time now. Some background: I created my automated test framework using Selenium. With one project being pure NUnit tests and second one that does all the work for the tests. Now, in test project I keep the directories to all environments I run my tests against. So far many of my tests were read-only and didn't bother much about if tests did not run on environment that they supposed to. This has changed as I started to run some 'write' tests.
I need to prevent this 'Write' tests to run on any other environment then localhost. So far I tried to use method attributes and getting test method names on run time and do work then but this is not quite efficient. Can you guys point me a good solution? Thanks!
I would tag the tests to exclude with a particular category name then define a SetUp function which will stop the tests from running if they are tagged with that name and if you are on a particular environment such as Production. Place the SetUp function in a BaseClass and have all your test fixtures inherit it. The SetUp function will run before every test and prevent it from running if it needs to.
Something like this:
public class BaseSetup
{
protected const string CategoryToExclude = "Write";
[SetUp]
public void Init()
{
string env = ConfigurationManager.GetEnvironment();
if ( env == Constants.Environments.PROD && (TestContext.CurrentContext.Test.Properties["Categories"].Contains(CategoryToExclude)))
{
Assert.Inconclusive(String.Format("Cannot run this test on environment: {0}", env));
}
}
}
[TestFixture]
public class UnitTests : BaseSetup
{
[Test]
[Category(CategoryToExclude)]
public void TestMethod1()
{
Console.WriteLine("TestMethod1");
}
[Test]
public void TestMethod2()
{
Console.WriteLine("TestMethod2");
}
}
Hope this helps!
NUnit have category attribute.
You can group tests by categories and run only wanted categories.

Curious problem with NUnit and Typemock

Using VS 2010, NUnit, Typemock, Entity Framework...
I am having a bit of an odd problem using NUnit/Typemock. I am relative new to the testing world so it could be a beginners mistake. This is the problem I am having.
Test Project is compiled.
Launch NUnit from within Visual Studio
Run tests from within NUnit client app. First run, first test always fails.
Rerun and test passes.
It does not matter what test is first. I can select a particular test. If it is the first one to run, it fails on first execution. It passes on rerun.
This is an example class having the problem. But the class doesn't matter. Whatever test is run first has this problem. The exception code was just something that was there to test Typemock being loaded. It fails on the WhenCalled.
[TestClass, Isolated]
public class FirstTest
{
[TestMethod]
public void TestMe()
{
Exception e = new TypeMock.ArrangeActAssert.NestedCallException();
Isolate.WhenCalled(() => UnitOfWorkManager.GetCurrentSession(null)).WillReturn(null);
Assert.IsTrue(true);
}
}
The following is the error message.
HCSO.ESL.Test.Fakes.FirstTest.TestMe:
TypeMock.ArrangeActAssert.NestedCallException :
* WhenCalled does not support using a property call as an argument.
- To fix this pass false instead of AssemblyReader.IsDotNetFile
Example - this would work:
MyObj argument = Something.Other().GetStuff();
Isolate.WhenCalled(() => ObjUnderTest.MethodUnderTest(argument))...;
Example - this would not work:
Isolate.WhenCalled(() => ObjUnderTest.MethodUnderTest(Something.Other().GetStuff()))...;
(End error message)
Anyone have an idea why the first test always fails but runs fine on rerun? Something with how the assemblies are being loaded?
(Edit)Additional Details:
Versions:
Typemock Isolator: 6.0.10.0
Visual Studio: 10.0.30319.1
In addition, I added simplified test code. This way you can see the code being tested. And yes, this test fails first time, passes on every run after that.
[TestClass, Isolated]
public class FirstTest
{
public static int DummyCall(int i)
{
return 0;
}
[TestMethod]
public void TestMe()
{
Exception e = new TypeMock.ArrangeActAssert.NestedCallException();
//Isolate.WhenCalled(() => UnitOfWorkManager.GetCurrentSession(null)).WillReturn(null);
Isolate.WhenCalled(() => FirstTest.DummyCall(-1)).WillReturn(1);
Assert.IsTrue(true);
}
}
I work at Typemock,
It seems very strange, as this is definitely not a nested call from the looks of it.
Could you please try and email us a small solution demonstrating the problem to support#typemock.com?
What is UnitOfWorkManager? Is this a class belonging to EF, or is it your code?
Also, what version of Isolator are you using?
I resolved the issue. As I expected, it was partially a newbie mistake. Inside of NUnit there is a setting to determine how the assembly is isolated. The default option is to run the tests in the same process as NUnit. I tried changing the isolation in a seperate process per assembly and the problem goes away.
To reproduce error.
* Make sure NUnit option for "Run tests directly in NUnit process" is selected.
* Close NUnit (just to make sure setting is used)
* Launch NUnit from within VS.
* Select a test containing Isolate.WhenCalled()
* Run that test first.
Thanks for the help.
[EDIT: Update]
Updating this in the event someone else has this issue.
I found that in the NUnit client if I set the following options everything works great.
Under Settings:
Test Loader -> Assembly Isolation -> Default Process Model -> Run test directly in the NUnit process.
Test Loader -> Assembly Isolation -> Default Domain Usage -> Use a seperate AppDomain per Assembly

MbUnit Integration Testing Newbie Question

I've been tasked with integration testing of a large system. Presently, I have a COM dll that I'm testing useing a UI that I created that kicks off a series of unit tests that call into the dll. This works, but I'm wanting to migrate this over to MbUnit. When I start the first test in MbUnit, it seems to hang at "Found 1 tests". I end up having to close the IDE. Could someone please point me in the right direction?
Thanks.
This is how we kick off our MBUnit test application (command line):
namespace UnitTest
{
class Program
{
static void Main(string[] args_)
{
// run unit test
AutoRunner auto = new AutoRunner();
auto.Load();
auto.Run();
HtmlReport report = new HtmlReport();
string fileName;
// generate report results
fileName = report.Render(auto.Result);
// launch results in user's browser
System.Diagnostics.Process.Start(fileName);
}
}
}
Try stepping through the code manually with a debugger.

Categories

Resources