类型定义应该以'{'开头,期望序列化类型为"ErrorResponse",但得到了一个以"MOCK FOR URL NOT FOUND"开头的字符串。

3
我正在使用Xunit和Moq编写一个单元测试,针对ServiceStack微服务进行测试。
我可以成功地对一个类的GET路由进行单元测试,但是对于另一个类,测试失败了。在这个路由中,我使用Moq对ServiceStack.JsonHttpClient.GET进行模拟。
public SampleResponse Get(SampleRequest request)
{
    var myServiceRequest = new SampleService.myRequest() { PrimaryId = request.PrimaryId };
    using (client = ClientFactory.CreateSampleService()) // client is extension of ServiceStack.JsonHttpClient
    {
        // This code runs on local but throws the exception with unit testing
        SampleService.myResponse myResponse = client.Get(myServiceRequest);
        ...
    }
}

以下是测试内容:

// Arrange
var myServiceRequest = new SampleService.myRequest { PrimaryId = 1234 };
var myServiceResponse = new SampleService.myResponse { ... };

 // assigning the request with the desired response
mockService.MockGet(myServiceRequest, myServiceResponse);

// Act
var request = new ServiceModel.SampleRequest { PrimaryId = 1234 };
 // This calls the above function and fails
var response = frontEndService.Get(request); 

// Assert
Assert.NotEmpty(response.Items);
Assert.Equal(3, response.Items.ANumber);

但是我得到了这个异常和内部异常:

ServiceStack.WebException: '未找到'

内部异常

SerializationException:类型定义应该以'{'开头,期望序列化类型“ ErrorResponse”,而得到的是以MOCK FOR URL NOT FOUND开头的字符串。

我几乎为一个更简单的类设置了完全相同的内容,并且它运行正常,但是这个类拒绝进行正确的单元测试。当本地运行时,它确实可以正常运行。

1个回答

2

当JSON与您尝试反序列化的类型不匹配时,将出现此异常。


1
嗨,mythz!我更新了我的问题;当我期望moq返回OcrWordsResponse时,从GET返回了一个ErrorReponse类型。我该如何排除为什么ServiceStack无法正确处理OcrDocumentRequest类型的问题? - Zorgarath
@Zorgarath 这个异常表明服务抛出了异常,你是否尝试调试你的服务实现? - mythz
我和我的团队成员都感到困惑,因为服务运行良好,但一旦这个对象被模拟并进行单元测试,ServiceStack就会抛出错误。我一直在努力找出更多关于异常抛出的原因。 - Zorgarath
@Zorgarath frontEndService 是你的服务类,对吧?所以 frontEndService.Get() 只是一个直接调用的方法,你可以进行调试。这里只是在调用 C# 方法。我也没有看到任何序列化操作,因为你只是传递了一个类型化的请求 DTO 并返回了一个类型化的响应 DTO。你的服务是否正在进行 HTTP 调用或执行任何序列化操作?如果是的话,那可能就是问题所在了。 - mythz
1
嗨,mythz,事实证明我们的 Moq 有一个错误的请求类型被映射到了正确的响应类型,并且一些内部代码掩盖了错误的起源。我们已经修复了它! - Zorgarath
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接