单元测试中的匿名类型

时间:2019-04-09 10:31:41

标签: c# unit-testing xunit anonymous-types

我正在编写一个应用程序,允许用户通过注册同一封电子邮件来“登录”。 (不用担心,它不是可以在互联网上运行的应用程序,也不包含关键数据。它是临时注册,只能在本地网络中运行。)MVC方法应该返回API密钥和成功登录后,一些其他数据。我创建了一个单元测试来检查此行为:

[Fact]
public void Register_ExistingEmail()
{
    //Arrange
    DbContext context = new DbContext(InMemoryDbContextOptionsExtensions.UseInMemoryDatabase(new DbContextOptionsBuilder<DbContext>(), "VoteInMemDb").Options);
    context.Users.Add(new User { ApiToken = "TestToken123", Email = "commonname@commondomain.com", JsonData = "{}" });
    context.SaveChanges();
    //logger, hub and settings are being mocked using Moq and are set up in the constructor
    RegistrationController regCon = new RegistrationController(logger, context, hub, settings);

    //Act
    IActionResult result = regCon.Register("commonname@commondomain.com", "{}", false);

    //Assert
    try
    {
        //attempt to cast to expected result type
        JsonResult jsonResult = (JsonResult)result;

        Assert.Equal(new
        {
            apiToken = "TestToken123",
            currentScreen = ClientScreen.welcome.ToString(),
            cookieDuration = settings.Value.ApiTokenDuration
        }, jsonResult.Value);
    }
    catch (EqualException e)
    {
        throw e;
    }
    catch
    {
        Assert.True(false);
    }
}

现在,即使它成功按预期返回了对象,它仍然会抛出EqualException

Testname:   project.unit_tests.UnitTest1.Register_ExistingEmail
FullName für Test:  project.unit_tests.UnitTest1.Register_ExistingEmail
Testquelle: D:\Repositories\project.unit-tests\UnitTest1.cs : Zeile 77
Testergebnis:   Fehler
Testdauer:  0:00:01.009

Ergebnis StackTrace:    at project.unit_tests.UnitTest1.Register_ExistingEmail() in D:\Repositories\project.unit-tests\UnitTest1.cs:line 104
Ergebnis Meldung:   
Assert.Equal() Failure
Expected: { apiToken = TestToken123, currentScreen = welcome, cookieDuration = 1440 } (<>f__AnonymousType0`3[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]])
Actual:   { apiToken = TestToken123, currentScreen = welcome, cookieDuration = 1440 } (<>f__AnonymousType1`3[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]])

除了<>f__AnonymousTypeX`3部分,我发现它是99%的相同对象。这是因为我使用匿名Types来生成JsonResults吗?我要为要对方法进行单元测试的每个匿名Type创建模型吗?

预先感谢

0 个答案:

没有答案