I originally posted a question on the asp.net docs and was referred here.
Moving from NET5 -> NET6 broke a lot of testing using the WebApplicationFactory since the public Startup.cs was removed. The alternative was moving to Program which worked until the new templates came about. In the new templates there is no public class program, so we needed to add a public partial class Program {}
I was looking at the docs and they offered a new solution using InternalsVisibleTo which is better imho since it does not change code just for testing purposes.
However that would lead to code like this
public class UnitTest1 : IClassFixture<WebApplicationFactory<Program>>
{
public UnitTest1(WebApplicationFactory<Program> applicationFactory)
{
}
}
The problem however is that Program is internal, which triggers CS0051:
UnitTest1.cs(8, 12): [CS0051] Inconsistent accessibility: parameter type 'WebApplicationFactory' is less accessible than method 'UnitTest1.UnitTest1(WebApplicationFactory)')
The problem with that is that xunit requires its class / constructor to be public.
So did anyone manage to get this working without the public partial?
If you just wanted to access the auto-generated
internalProgramclass in your test project,[InternalsVisibleTo]would work.However, you're trying to use an
internaltype as a type parameter to apublictype, and expect thatpublic<internal>type to bepublicly accessible.Imagine a scenario with 3 assemblies:
A,B,C.AdefinesinternalclassInternalImpland has[InternalsVisibleTo("B")]set,Bdefinespublictype as follows:In the above example,
AnIllegalPublicPropertyis illegal, because though assemblyBhas access to typeInternalImplthe type is still internal and wont be accessible to assemblyC(or any other assembly for that matter).Infact, though
AnotherPublicTypeis a public class, C# would not allowAnotherPublicType<InternalImpl>to be more accessible than internal, because the highest-allowed accessibility is the lowest accessibility of the type (AnotherPublicType) and its type arguments (InternalImpl). Changing that property to the following would work:For more information, check the spec §7.5.3 Accessibility domains:
To answer your question, either
WebApplicationFactorymust be madeinternal(along withIClassFixtureand alsoUnitTest1) orProgrammust be madepublic.I believe xunit requires tests to be public.
So, your only option is to add the following to the end of your
Program.csfile: