[英]Unit Testing Stops In Middle When I use Console.Readline()
I want to mock Console.ReadLine()
using MOQ but I do not know how to do that.我想使用 MOQ 模拟Console.ReadLine()
但我不知道该怎么做。 I tried to search on the internet but I couldn't find an appropriate answer.我试图在互联网上搜索,但找不到合适的答案。 I have tried various things but none had worked so far.我尝试了各种方法,但到目前为止都没有奏效。 This is just a demo file.这只是一个演示文件。 I am working on a console app where I have to use Console.ReadLine()
.我正在开发一个必须使用Console.ReadLine()
的控制台应用程序。 But I do not know how to mock the function that is using Console.ReadLine()
.但我不知道如何模拟使用Console.ReadLine()
的 function 。
using System;
namespace _Calci
{
public class Operands
{
public int num1;
public int num2;
}
public class ret
{
public virtual int _ret()
{
return (Int32.Parse(Console.ReadLine()));
}
}
public class Calci : ret
{
ret retObj = new ret();
public int Multiply()
{
int result;
int num1 = 4;
result = retObj._ret() * num1;
return result;
}
}
}
Unit Testing File:单元测试文件:
using Xunit;
using _Calci;
using Moq;
namespace Testings
{
public class Testing
{
[Fact]
public void MultiplyTesting()
{
Mock<ret> mockingVar = new Mock<ret>();
mockingVar.Setup(x=> x._ret()).Returns(()=>5);
Calci calciObj = new Calci();
int expected = 20;
int actual = calciObj.Multiply();
Assert.Equal(expected, actual);
}
}
}
In your Calci
class inject through constructor ret
object instead of making a new instance inside the Calci
.在您的Calci
class 中,通过构造函数ret
object 注入,而不是在Calci
中创建一个新实例。 Then in your test you'll be able to inject mocked ret
that returns any int like this: Calci calciObj = new Calci(mockingVar.Object);
然后在您的测试中,您将能够注入返回任何 int 的模拟ret
,如下所示: Calci calciObj = new Calci(mockingVar.Object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.