我想使用Moq / Nunit在基本抽象类IsAdult
中使用moq Person
方法。每当我运行测试时,它都会调用基类IsAdult
类中的实际方法Person
,而不是在设置中返回值。我的代码如下所示
public abstract class Person
{
public string Gender { get; set; }
public int Age { get; set; }
public virtual bool IsAdult()
{
return this.Age >= 18;
}
protected Person(string gender, int age)
{
this.Gender = gender;
this.Age = age;
}
}
public class Employee : Person
{
public decimal Salary { get; set; }
public Employee() : base("Male", 17)
{
}
public string ProcessSalary()
{
if (IsAdult())
{
// process the salary
return "Processed";
}
return null;
}
}
[TestFixture]
public class PersonTest
{
[Test]
public void Some_Name()
{
var person = new Mock<Person>() { CallBase = true };
person.Setup(x => x.IsAdult()).Returns(true);
var employee = new Employee();
var result = employee.ProcessSalary();
Assert.AreEqual("Processed", result);
}
}
如何解决此设置的任何想法?
答案 0 :(得分:1)
using Moq;
using Xunit;
namespace MockAbstractClass
{
public class EmployeeTests
{
[Fact]
public void IsAdultMock()
{
var employeeMock = new Mock<Employee>() { CallBase = false };
employeeMock.Setup(x => x.IsAdult()).Returns(true);
var employee = employeeMock.Object;
var result = employee.IsAdult();
Assert.True(result);
}
[Fact]
public void Some_Name()
{
var employeeMock = new Mock<Employee>() { CallBase = true };
employeeMock.Setup(x => x.IsAdult()).Returns(true);
var employee = employeeMock.Object;
var result = employee.ProcessSalary();
Assert.Equal("Processed", result);
}
}
}
而不是模拟Person模拟Employee.IsAdult属性。现在一切都按预期工作了。