有没有办法创建一个模拟对象,只模拟其中一个属性,让其他(属性和方法)链接到原始类,而不必模拟所有方法
测试方法 - >
var test= new Mock<Test>().As<ITest>();
test.CallBase = true;
test.SetupGet(m => m.DateNow).Returns(DateTime.Now.AddDays(10));
double num= test.Object.Calc();
Run Code Online (Sandbox Code Playgroud)
界面 - >
public interface ITest
{
double Calc();
DateTime DateNow { get; }
}
Run Code Online (Sandbox Code Playgroud)
班级 - >
public class Test : ITest
{
public DateTime DateNow
{
get
{
return DateTime.Now.Date;
}
}
public double Calc(){
DateTime d = DateTime.Now.AddDays(100);
return (DateNow - d).TotalDays;
}
Run Code Online (Sandbox Code Playgroud)
总是num = 0.0;
我正在将moq与nunit一起使用,而我的测试并没有使我失败或通过。它说它没有默认的构造函数。我怀疑我在将接口注入构造函数中做不到正确的事情。
捐助者管理测试
[TestFixture]
public class DonorManagementTests
{
private readonly Mock<IValidation> _mockValidation;
private readonly DonorManagement _donorManagement;
public DonorManagementTests(IValidation validation)
{
_mockValidation = new Mock<IValidation>();
_donorManagement = new DonorManagement(_mockValidation.Object);
}
[Test, Description("View correct gift aid to two decimal places")]
public void DonorViewGiftAid()
{
const int donation = 20;
_mockValidation.Setup(x => x.ValidateDonation(donation)).Returns(20.00m);
var res = _donorManagement.GiftAidAmount(donation);
Assert.IsInstanceOf(typeof (decimal), res);
_mockValidation.Verify(x => x.ValidateDonation(donation), Times.Once);
}
}
Run Code Online (Sandbox Code Playgroud)
捐助者管理
public class DonorManagement : IDonor
{
private readonly IValidation _validation;
public DonorManagement(IValidation validation)
{
_validation = validation; …Run Code Online (Sandbox Code Playgroud) 我想对一个用于验证用户的类AuthClient(使用Moq)进行单元测试.
问题是我的AuthenticationService依赖关系没有注入课堂.我对如何在不注入依赖项的情况下测试流程感到困惑.
[TestClass]
public class AuthClient
{
string Dictionary<string, IList<UserPermissions> _userPermissions;
User Login(string username, string password)
{
IAuthenticationService authenticationService = new AuthenticationService();
User user = authService.Login(username, password);
IAuthorizationService authorizationService = new AuthorizationService();
var permissions = authorizationService.GetPermissions(user);
_userPermissions.Add(user.Username, permissions);
return user;
}
}
Run Code Online (Sandbox Code Playgroud)
我目前的单元测试代码如下:
public class UnitTestClass
{
public string UserName {get;set;}
public string Password {get;set;}
[TestInitialize]
public void Setup()
{
UserName = "test";
Password = "test123";
}
[TestMethod]
public void When_ValidUserCredentials_Expect_UserIsNotNull()
{
var mockAuthenticationService …Run Code Online (Sandbox Code Playgroud) 我试图围绕一些通过Nest访问Elasticsearch的代码编写一些单元测试,特别是.Search()调用.我正在尝试设置Moq以在.Search()调用时返回空搜索响应:
var emptyResponse = new Nest.SearchResponse<MyDoc>()
{
Documents = new List<MyDoc>() // illegal
};
esClient.Setup(x => x.Search<MyDoc>(It.IsAny <Func<SearchDescriptor<MyDoc>, SearchDescriptor<MyDoc>>>())).Returns(emptyResponse);
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不能这样做,因为Documents只读SearchResponse.围绕搜索调用编写单元测试的建议方法是什么?
我正在使用Moq框架进行模拟.我发现Equals覆盖不能按预期工作的问题.似乎动态对象中必须有一个总是返回false的覆盖.这是一些示例代码.我正在使用nuget的Moq版本4.2.1507.0118.
public class B
{
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
class Program
{
static void Main(string[] args)
{
var a = new Moq.Mock<B>().Object;
var b = a;
bool equalsOperator = a == b; //returns true
bool referenceEquals = object.ReferenceEquals(a, b); //returns true
bool equals_b = a.Equals(b); //returns false
bool equals_a = a.Equals(a); //returns false
}
}
Run Code Online (Sandbox Code Playgroud)
另一个有趣的事情是,如果断点放在Equals覆盖上,它永远不会被击中.Moq框架中是否存在错误,或者是否存在我做错的事情?
我正在使用Moq对我们使用Entity Framework的一些代码进行单元测试.在我的单元测试中,我有以下代码,但是当我测试它时,我无法获得正确的返回值(一切编译好,但计数结果为0,返回null).这告诉我,我的Entity对象从未添加到我的模拟仓库中.
[TestMethod]
public void GetEntity_ValidName_EntityReturned()
{
Entity testEntity = new Entity();
testEntity.Name = "Test";
var mockService = new Mock<IUnitOfWork>();
mockService.Setup(mock => mock.EntityRepo.Add(testEntity));
IUnitOfWork testDB = mockService.Object;
testDB.EntityRepo.Add(testEntity);
Entity testEntity2 = EntityHelper.getEntity(testDB,testEntity.Name);
int count = testDB.EntityRepo.Count();
Assert.AreEqual(testEntity.Name,testEntity2.Name);
}
Run Code Online (Sandbox Code Playgroud)
如何添加实体?我还需要吗?我也尝试了以下无法编译:
mockService.Setup(mock => mock.EntityRepo.Add(testEntity)).Returns(testEntity);
Run Code Online (Sandbox Code Playgroud)
同上:
mockService.SetupGet(mock => mock.EntityRepo.Add(testEntity)).Returns(testEntity);
Run Code Online (Sandbox Code Playgroud)
编辑:这是测试的目标:
public static Entity getEntity(IUnitOfWork database, string entityName)
{
Entity _entity = database.EntityRepo.Find(x => x.Name.ToLower().Trim() == entityName).FirstOrDefault();
return _entity;
}
Run Code Online (Sandbox Code Playgroud) 我是一个界面,它有:
Dictionary<string, object> InstanceVariables { get; set; }
我已经创建了一个新的界面模拟并试图设置它,所以它只返回一个随机字符串,如下所示:
_mockContext.SetupGet(m => m.InstanceVariables[It.IsAny<string>()]).Returns(@"c:\users\randomplace");
但我似乎得到一个错误:
{"Invalid setup on a non-virtual (overridable in VB) member: m => m.InstanceVariables[It.IsAny<String>()]"}
这究竟是什么意思?我在嘲笑界面所以不应该这不是问题吗?
谢谢
我刚开始使用Moq&FluentAssertions并找到:
results.Results.Count.Should().Equals(1);
Run Code Online (Sandbox Code Playgroud)
在代码中,results.Results返回类List列表.在测试设置中,我将其设置为results.Results.Count = 3(我可以看到这个#在调试中也是正确的).但不知何故,上面的.Equals测试通过了.然后我把它改成了
results.Results.Count.Should().Equals("1");
Run Code Online (Sandbox Code Playgroud)
它仍然过去了.如果我使用它将失败
results.Results.Count.ShouldBeEquivalentTo(1);
Run Code Online (Sandbox Code Playgroud)
所以,问题是:
结果.Count.Should().等于("1")比较?为什么它过去了?
谢谢
我不确定我会怎么做.
鉴于我有
public interface IFactory<T> where T : new()
{
IWrapper<T> GetT(string s);
}
public interface IWrapper<out T> where T : new()
{
void Execute(Action<T> action);
}
Run Code Online (Sandbox Code Playgroud)
当我这样做
public class MoqTest
{
public void test()
{
Mock<IWrapper<basicClass>> wrapperMock = new Mock<IWrapper<basicClass>>();
Mock<IFactory<basicClass>> factoryMock = new Mock<IFactory<basicClass>>()
.Setup(p => p.GetT(It.IsAny<string>()))
.Returns(wrapperMock.Object);
}
}
Run Code Online (Sandbox Code Playgroud)
我明白了
无法隐式转换
Moq.Language.Flow.IReturnsResult<TestNamespace.IFactory<TestNamespace.basicClass>>为Moq.Mock<TestNamespace.IFactory<TestNamespace.basicClass>>.存在显式转换(您是否错过了演员?)
请注意,这些只是模拟的示例对象.
它似乎不考虑返回类型等价.一个是a IReturnResult,另一个是aMoq.Mock
我有ChangePassword方法,我必须User.Identity.GetUserId()找到UserId.
问题:它总是返回null.不明白为什么.
我在另一篇文章中读到了GetUserById使用下面的代码行查找Id.我不知道如何嘲笑ClaimsTypes.NameIdentifier.
return ci.FindFirstValue(ClaimTypes.NameIdentifier);
ChangePassword方法(单位测试的方法)
public async Task<IHttpActionResult> ChangePassword(string NewPassword, string OldPassword)
{
_tstService = new TestService();
IdentityResult result = await _tstService.ChangePassword(User.Identity.GetUserId(), OldPassword, NewPassword);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
单元测试
var mock = new Mock<MyController>();
mock.CallBase = true;
var obj = mock.Object;
obj.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };
obj.Request.SetOwinContext(CommonCodeHelper.mockOwinContext());
IPrincipal user = GetPrincipal();
obj.ControllerContext.RequestContext.Principal = user;
var result = …Run Code Online (Sandbox Code Playgroud)