moq

Moq Sequence with Callback C#

久未见 提交于 2020-12-12 05:12:53
问题 I have this code below with a simple nunit test using Moq Sequence. The unit test works without using Callback, but it fails with Callback. Any ideas? public class MoqDemo { private ISender sender; public MoqDemo(ISender sender) { this.sender = sender; } public void Send() { for (int i = 0; i < 3; i++) { sender.SendMessage(i, $"{i}"); } } } NUnit test [TestFixture] public class MoqDemoTest { [Test] public void SequenceTest() { var sender = new Mock<ISender>(); using (Sequence.Create()) { var

Mock method return based on object parameter

橙三吉。 提交于 2020-12-11 09:00:42
问题 I have the following (simplified) code: public string methodName(ClassType object) { If(object.value == 1) return "Yes"; else If(object.value == 2) return "No"; else return "whatever"; } I am then calling this method in a unit test, and need to mock the return type based on the object value: _Service.Setup(x => x.methodName(new methodName { value = 1}).Returns("Yes"); _Service.Setup(x => x.methodName(new methodName { value = 2}).Returns("No"); I know what I have written is wrong - but how can

Mock method return based on object parameter

人盡茶涼 提交于 2020-12-11 08:59:30
问题 I have the following (simplified) code: public string methodName(ClassType object) { If(object.value == 1) return "Yes"; else If(object.value == 2) return "No"; else return "whatever"; } I am then calling this method in a unit test, and need to mock the return type based on the object value: _Service.Setup(x => x.methodName(new methodName { value = 1}).Returns("Yes"); _Service.Setup(x => x.methodName(new methodName { value = 2}).Returns("No"); I know what I have written is wrong - but how can

C# Mock IHttpclient & CreateClient

南楼画角 提交于 2020-12-05 12:01:54
问题 I have a function that I want to x-unit test, but it seems that I have to mock the CreateClient function? Whenever I debug it during testing it seems that the var client is equals to null. I am injecting the dependencies properly, I am sure of that. What I want to know is how to mock the CreateClient. here is that function: public async Task CreateMessageHistoryAsync(Message message) { //This seems to be giving a null value var client = this.clientFactory.CreateClient(NamedHttpClients.COUCHDB

.net core grpc单元测试

妖精的绣舞 提交于 2020-10-02 11:26:47
前言 gRPC凭借其严谨的接口定义、高效的传输效率、多样的调用方式等优点,在微服务开发方面占据了一席之地。dotnet core正式支持gRPC也有一段时间了,官方文档也对如何使用gRPC进行了比较详细的说明,但是关于如何对gRPC的服务器和客户端进行单元测试,却没有描述。经过查阅官方代码,找到了一些解决方法,总结在此,供大家参考。 本文重点介绍gRPC服务器端代码的单元测试,包括普通调用、服务器端流、客户端流等调用方式的单元测试,另外,引入sqlite的内存数据库模式,对数据库相关操作进行测试。 准备gRPC服务端项目 使用dotnet new grpc命令创建一个gRPC服务器项目。 修改protos/greeter.proto, 添加两个接口方法: // 服务器流 rpc SayHellos (HelloRequest) returns (stream HelloReply); // 客户端流 rpc Sum (stream HelloRequest) returns (HelloReply); 在GreeterService中添加方法的实现: using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Grpc.Core;