简体   繁体   English

使用Visual Studio单元测试框架比较两个对象

[英]Comparing two objects with Visual Studio Unit Testing Framework

I'm using TDD to develop an Android mobile game with Unity. 我正在使用TDD与Unity一起开发Android手机游戏。 I isolated the core logic inside normal classes. 我在普通类中隔离了核心逻辑。 Currently, I'm intend to test the following scenario : Player or AI activates the "End turn" option and the game manager goes to the next character waiting for its turn. 当前,我打算测试以下场景:玩家或AI激活“结束回合”选项,游戏管理器转到下一个角色,等待其回合。

I tried to use AreEqual, AreNotEqual, AreSame, AreNotSame methods from the framework. 我尝试从框架中使用AreEqual,AreNotEqual,AreSame,AreNotSame方法。 AreSame and AreNotSame returned with failed. AreSame和AreNotSame返回失败。 AreEquals and AreNotEquals returned with the following exception: "AssertFailException". AreEquals和AreNotEquals返回以下异常:“ AssertFailException”。 I verified by debbuging my test that both references are not null. 我通过调试测试来验证两个引用都不为空。 I have overridden the Equals and GetHashCode from compare 2 objects and made sure that the class I'm trying to check in my test implemented the interface IEqualityComparer. 我从比较2个对象覆盖了Equals和GetHashCode,并确保我要在测试中检查的类实现了IEqualityComparer接口。 I'm trying to figure out what's wrong but I can't. 我正在尝试找出问题所在,但我不能。 Basically my test is doing the following : 基本上我的测试是在做以下事情:

  1. Generating the game manager 生成游戏管理器
  2. Generating the characters of the game 生成游戏角色
  3. Add two sample characters to the list of characters 将两个示例字符添加到字符列表中
  4. Creating an EndTurnCommand object 创建一个EndTurnCommand对象
  5. Activate the first player 激活第一个玩家
  6. Make the first player call end turn and activate the next character (second sample character) 使第一个玩家通话结束并激活下一个角色(第二个示例角色)
  7. Compare previous active character and current and make sure that they're not the same 比较以前的活动角色和当前角色,并确保它们不相同

Below you can find the TestMethod 在下面可以找到TestMethod

        var gm = new Assets.GameCoreLogic.Managers.GameManager();
        gm.GenerateCharacters();
        var characGen = new CharacterGenerator();
        var stats = new BaseCharacterStats();
        stats.StatGeneration(500, 1, 1, 1, 1, 1, 1, 1);
        var charac = characGen.Generate(new Health((int)stats.HealthPoints), stats, PlayerDirection.Down);
        var secondCharac = characGen.Generate(new Health((int)stats.HealthPoints+1), stats, PlayerDirection.Up);
        gm.EveryCharacters.Add(charac);
        gm.EveryCharacters.Add(secondCharac);
        var gcm = new GameCommandMenu();
        var etc = new EndTurnCommand(gcm);
        gm.ActivatePlayer(0);
        var active = gm.ActivePlayer;
        etc.Execute(active,gm);
        Assert.AreNotSame(active, gm.ActivePlayer);

To make sure that the TestMethod can make sense for readers, I'm putting the source code for EndTurnCommand (Command Pattern object), BaseCharacter(with properties and the override methods), the Generate method from CharacterGenerator. 为了确保TestMethod对读者有意义,我将放置EndTurnCommand(命令模式对象),BaseCharacter(带有属性和重写方法),CharacterGenerator中的Generate方法的源代码。

EndTurnCommand EndTurnCommand

    public class EndTurnCommand: CharacterActions
{
    public EndTurnCommand(IReceiver receiver) : base(receiver)
    {
    }

    public void Execute(BaseCharacter caller, GameManager manager)
    {
        if (caller == null)
            throw new ArgumentException();            
        if(manager == null)
            throw new ArgumentException();

        manager.GoToNextCharacter();
    }
}

BaseCharacter 基本字符

    public class BaseCharacter: IEqualityComparer<BaseCharacter>
{
    public BaseCharacterStats BaseStats { get; set; }
    public Health Health { get; set; }
    public PlayerDirection Direction;
    public List<BaseEnemy> CurrentEnnemies;
    public List<BaseCharacter> TeamMembers;
    public int MovementPoints = 4;
    public GameMap GameMap;
    public Cell CurrentCoordinates;
    public bool IsDead; //Testing

    public BaseCharacter(Health health = null, BaseCharacterStats stats = null, PlayerDirection direction = default(PlayerDirection))
    {
        BaseStats = stats;
        Health = health;
        Direction = direction;
        CurrentEnnemies = new List<BaseEnemy>();
        TeamMembers = new List<BaseCharacter>();
    }

    public bool Equals(BaseCharacter x, BaseCharacter y)
    {
        if (ReferenceEquals(x, y)) return true;

        if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false;

        return x.IsDead == y.IsDead &&
               x.Health.CurrentHealth == y.Health.CurrentHealth &&
               x.Health.StartingHealth == y.Health.StartingHealth &&
               x.BaseStats.Power == y.BaseStats.Power &&
               x.BaseStats.Defense == y.BaseStats.Defense &&
               x.BaseStats.MagicPower == y.BaseStats.MagicPower &&
               x.BaseStats.MagicResist == y.BaseStats.MagicResist &&
               x.BaseStats.Luck == y.BaseStats.Luck &&
               x.BaseStats.Speed == y.BaseStats.Speed &&
               x.BaseStats.Agility == y.BaseStats.Agility &&
               x.Direction == y.Direction;
    }

    public int GetHashCode(BaseCharacter obj)
    {
        var hashCodeStats = obj.BaseStats?.GetHashCode() ?? 0;
        var hasCodeHealth = obj.Health?.GetHashCode() ?? 0;
        var hasCodeDirection = obj.Direction.GetHashCode();
        return hashCodeStats ^ hasCodeHealth ^ hasCodeDirection;
        }
}

CharacterGenerator 角色生成器

public class CharacterGenerator
{
    public BaseCharacter Generate(Health h, BaseCharacterStats bcs, PlayerDirection pd)
    {
        return new BaseCharacter(h,bcs,pd);
    }
}

Can you try to change your Equals signature to this? 您可以尝试将您的Equals签名更改为此吗?

public override bool Equals(object obj)
{
    BaseCharacter that = (BaseCharacter)obj;
    return this.IsDead == that.IsDead
        && this.Health.CurrentHealth == that.Health.CurrentHealth;
}

== updated == ==更新==

I went ahead an implement a simple class and a test case. 我继续执行一个简单的类和一个测试用例。 Maybe it's easier for you to spot the difference. 也许更容易发现差异。

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            XCharacter x = new XCharacter() { isDead = true, Health = 100 };
            YCharacter y1 = new YCharacter() { isDead = true, Health = 100};
            YCharacter y2 = new YCharacter() { isDead = true, Health = 0 };
            Assert.AreEqual(x, y1); //ok 
            Assert.AreNotEqual(x, y2); //ok
            Assert.AreEqual(x,y2); // not ok
        }
    }

    public abstract class BaseCharacter
    {
        public bool isDead { get; set; }
        public int Health { get; set; }

        public override bool Equals(object obj)
        {
            BaseCharacter that = (BaseCharacter)obj;
            return this.isDead == that.isDead && this.Health == that.Health;
        }
    }

    public class XCharacter : BaseCharacter
    {
    }

    public class YCharacter : BaseCharacter
    {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Visual Studio单元测试框架或NUnit框架在C#中模拟对象? - How to mock objects in C# using Visual Studio Unit Testing framework or NUnit framework? 我可以使用Visual Studio单元测试框架强制对属性进行单元测试吗? - Can I force unit testing of properties using the Visual Studio unit testing framework? Visual Studio 2010单元测试 - Visual Studio 2010 Unit Testing 用于单元测试 .net 标准库的框架/视觉工作室项目类型? - Framework/visual studio project type to use for unit testing .net standard libray? .NET在Visual Studio中如何识别一个项目用的是什么单元测试框架? - How to recognize what unit testing framework is used in a project in Visual Studio, .NET? 比较两个DataTables(单元测试,集成测试,C#,TestMethod) - Comparing two DataTables (Unit Testing, Integration Testing, C#, TestMethod) Visual Studio 2012中的依赖(程序)单元测试 - Dependent (Procedural) Unit Testing in Visual Studio 2012 初学者介绍Visual Studio 2008中的单元测试 - Beginners introduction to unit testing in Visual Studio 2008 崩溃的 Visual Studio Live 单元测试 - Crashing Visual Studio Live Unit Testing C#Visual Studio中的单元测试 - Unit-testing in C# Visual Studio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM