mongodb 如何从控制器操作反序列化OkResult

bfnvny8b  于 2023-03-29  发布在  Go
关注(0)|答案(1)|浏览(217)

我尝试使用模拟测试为我的API创建xUnit,该API使用MongoDB的DataAccess层。但由于某种原因,它无法将OkResult解析为JSON或BSON。我肯定知道调试器需要两个值:

我的模型是:

namespace DataAccess.Models;
[BsonIgnoreExtraElements]
public class CyberGood
{
    [BsonId]
    [BsonElement("id")]
    public ObjectId Id { get; set; }

    [BsonElement("name")]
    public string Name { get; set; }

    [BsonElement("description")]
    public string Description { get; set; }

    [BsonElement("insideOf")]
    public string? InsideOf { get; set; }

    [BsonElement("madeIn")]
    public string MadeIn { get; set; }

    [BsonElement("price")]
    public decimal Price { get; set; }

    [BsonElement("amount")]
    public int Amount { get; set; }
}

我的控制器是:

[Route("api/[controller]")]
[ApiController]
public class CyberGoodController : ControllerBase
{
    private readonly ICyberGoodService _cyberGoodService;

    public CyberGoodController(ICyberGoodService cyberGoodService)
    {
        _cyberGoodService = cyberGoodService;
    }

    [HttpGet]
    public async Task<IActionResult> GetAllCyberGoodAsync()
    {
        try
        {
            var cyberGoods = await _cyberGoodService.GetAllCyberGoodAsync();
            return Ok(cyberGoods);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

我的测试用例:

[Fact]
[Obsolete]
public async Task GetAll_CyberGoods_ReturnsList()
{
    //Arrange
    var mock = new Mock<ICyberGoodService>();
    mock.Setup(d => d.GetAllCyberGoodAsync()).ReturnsAsync(GetTestCyberGoods());
    var service = new CyberGoodController(mock.Object);
    var objectSerializer = new ObjectSerializer(type => ObjectSerializer.DefaultAllowedTypes(type) 
    || type.FullName.StartsWith("DataAccess") 
    || type.FullName.StartsWith("Microsoft.AspNetCore.Mvc.OkObjectResult")); 
    BsonSerializer.RegisterSerializer(objectSerializer);

    //Act
    IActionResult result = await service.GetAllCyberGoodAsync();
    var bsonRes = BsonSerializer.Deserialize<List<CyberGood>>(result.ToBson());

    //Assert
    Assert.Equal(GetTestCyberGoods().Count, bsonRes.Count);

}

但不是一些测试结果,它给了我这个错误:
消息:MongoDB.Bson.BsonSerializationException:序列化Microsoft.AspNetCore.Mvc.ObjectResult类的Value属性时出错:类型System.Collections.Generic.List 1[[DataAccess.Models.CyberGood, DataAccess, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] is not configured as an allowed type for this instance of ObjectSerializer. ---- MongoDB.Bson.BsonSerializationException : Type System.Collections.Generic.List 1DataAccess.Models.CyberGood,DataAccess,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null未配置为此ObjectSerializer示例允许的类型。
堆栈跟踪:BsonClassMap串行化器1.SerializeMember(BsonSerializationContext context, Object obj, BsonMemberMap memberMap) BsonClassMapSerializer 1.串行化类(BsonSerializationContext上下文、BsonSerializationArgs参数、TClass文档)BsonClassMap序列化器1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TClass value) IBsonSerializer.Serialize(BsonSerializationContext context, BsonSerializationArgs args, Object value) ObjectSerializer.SerializeDiscriminatedValue(BsonSerializationContext context, BsonSerializationArgs args, Object value, Type actualType) ObjectSerializer.Serialize(BsonSerializationContext context, BsonSerializationArgs args, Object value) DiscriminatedInterfaceSerializer 1.序列化(BsonSerializationContext上下文,BsonSerializationArgs参数,TInterface值)IBsonSerializer.Serialize(BsonSerializationContext上下文,BsonSerializationArgs参数,Object值)BsonExtensionMethods.ToBson(对象obj,类型nominalType,BsonBinaryWriterSettings编写器设置,IBsonSerializer串行化程序,操作1 configurator, BsonSerializationArgs args) BsonExtensionMethods.ToBson[TNominalType](TNominalType obj, IBsonSerializer 1串行化程序,BsonBinaryWriterSettings编写器设置,Action 1 configurator, BsonSerializationArgs args) CyberGoodControllerTests.GetAll_CyberGoods_ReturnsList() line 30 --- End of stack trace from previous location --- ----- Inner Stack Trace ----- ObjectSerializer.SerializeDiscriminatedValue(BsonSerializationContext context, BsonSerializationArgs args, Object value, Type actualType) ObjectSerializer.Serialize(BsonSerializationContext context, BsonSerializationArgs args, Object value) IBsonSerializer.Serialize(BsonSerializationContext context, BsonSerializationArgs args, Object value) IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value) BsonClassMapSerializer 1.SerializeNormalMember(BsonSerializationContext context,Object obj,BsonMemberMap memberMap)BsonClassMapSerializer`1.SerializeMember(BsonSerializationContext context,Object obj,BsonMemberMap memberMap)

fhg3lkii

fhg3lkii1#

不要认为BsonSerializer可以序列化/反序列化IActionResult类型的值。
相反,
1.将result转换为OkObjectResult类型。并AssertokResult不为null以证明该操作返回OkObjectResult
1.提取okResult.Value并将其强制转换为List<CyberGood>类型。并AssertbsonRes不为null以证明值为List<CyberGood>类型。
1.最后,您可以执行Assert来匹配计数。

IActionResult result = await service.GetAllCyberGoodAsync();
var okResult = result as OkObjectResult();

// Validate result returned as OkResult
Assert.NotNull(okResult);
var bsonRes = okResult.Value as List<CyberGood>;

// Assert bsonRes is List<CyberGood> type
Assert.NotNull(bsonRes);

// Assert
Assert.Equal(GetTestCyberGoods().Count, bsonRes.Count);

相关问题