问题描述:

//Page 40: Unit Test for Player class

//Player must have a health that is greater than 0

//When the character is created.

namespace UnitTestingSample

{

class PlayerTests

{

public bool TestPlayerIsAliveWhenBorn()

{

Player p = new Player(); //ERROR: 'UnitTestingSample.Player.Player()' is inaccessible due to its protection level

if (p.Health > 0)

{

return true; //pass test

}

return false; //fail test

}//end function

}//end class

}//end namespace

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

//Page 41

//Player class has default health which is 10

//when his character is created

namespace UnitTestingSample

{

class Player

{

public int Health { get; set; }

Player() //constructor

{

Health = 10;

}

}

}

===============

You see, this is what makes me sad.

This code comes from Book named "C# Game Programming: For Serious Game Creation".

I got an exactly same code from the CD-ROM of this book. That sample code is fine while mine has an error.

This is my first time to write game-coding using C#. However, as I understood, mine should work. But, looks like compiler does not think so.

How can I fix this?

网友答案:
class Player
{
    public int Health { get; set; }

    public Player() //constructor
    {
        Health = 10;
    }
}

Class members are private by default and so is your constructor - which results in being inaccessible by your testing code. Make the constructor public if you want to access it from somewhere else than the class itself.

网友答案:

I had a similar problem and found this blog article was very helpful http://softwareonastring.com/316/why-cant-my-test-access-a-public-constructor

The specific solution it suggests is to add the following line to the project you want to test AssemblyInfo.cs file

[assembly: InternalsVisibleTo("TestProject")]

(Where TestProject is changed to the name of your test project assembly)

As well as right clicking on the references in your unit test project and adding a reference to the project you are testing.

This is only recommended for unit tests as it couples the two projects together tightly and would work against normal object oriented best practice.

相关阅读:
Top