JDavila JDavila - 3 months ago 13
C# Question

Why is the class not accessible in unit test?

I have created a unit test for a method in a class called game.cs. For some reason, when I reference the class, I am unable to create a new instance. How do I make this class accessible so I can test my code?

File Hierarchy and solution:

enter image description here

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BowlingKataTDD;

namespace BowlingKataTDDTest
{
[TestClass]
public class BowlingKataTDDUnitTests
{
[TestMethod]
public void DoesGameExist()
{
//arrange
BowlingKataTDD.
}
}
}


BowlingKataTDD Project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BowlingKataTDD
{
class Game
{
static void Main(string[] args)
{
}
}
}

Answer

The reason you do not see the classes is that they are non-public (internal by default).

There are two solutions to this:

  • If you would like to make your classes visible to outside users, make them public
  • If you would rather not publish your classes, use InternalsVisibleTo attribute.

To use the second solution, open AssemblyInfo.cs and add the following line:

[assembly: InternalsVisibleTo("BowlingKataTDDTest")]

BowlingKataTDDTest is the name of your assembly, as defined in the project file.