测试方法的参数是否已更改

Test that an argument to a method has been changed

我正在尝试使用 xUnit 和 Moq 编写一些测试,但我似乎无法理解如何测试提供给方法的参数是否已被方法本身更改。

这是我拥有的:

[Fact]
public void WhenCreateAsyncCalledSomePropertyIsSet()
{
    // Arrange
    var mockSomeService = new Mock<ISomeService>();
    var someObject = new SomeObject();

    // Act
    mockSomeService.Setup(x => x.CreateAsync(someObject)).Callback(() => {
        someObject.SomeProperty = "SomeValue";
    });

    // Assert
    Assert.NotNull(someObject.SomeProperty);
}

基本上我要做的是确保在调用 CreateAsync(someObject) 时设置 someObject 参数的 SomeProperty 属性。我的测试失败了..

更新:

我正在尝试测试以下方法:

public class SomeService : ISomeService
{
    private readonly SomeContext _context;

    public SomeService(SomeContext context)
    {
        _context = context;
    }

    public async Task CreateAsync(SomeObject someObject)
    {
        someObject.SomeProperty = GenerateRandomString();

        _context.SomeObjects.Add(project);

        await _context.SaveChangesAsync();
    }
}

我想测试调用方法时是否设置了 SomeProperty(如上)。如果我忘记设置它,我希望测试失败。

该服务与 SomeContext 实施问题紧密耦合。除非您打算进行内存中测试,否则上下文会导致一些并发症。

抽象上下文。

public interface ISomeContext {
    ISomeSet<SomeObject> SomeObjects { get; set; }
    Task<int> SaveChangesAsync(); 
}

class 将进行重构,使其不再依赖于实现问题并提供更大的灵活性。

public class SomeService : ISomeService {
    private readonly ISomeContext _context;

    public SomeService(ISomeContext context) {
        _context = context;
    }

    public async Task CreateAsync(SomeObject someObject) {
        someObject.SomeProperty = GenerateRandomString();    
        _context.SomeObjects.Add(project);    
        await _context.SaveChangesAsync();
    }

    string GenerateRandomString() {
        //...other code
    }
}

测试将模拟被测对象的依赖项的功能,并在执行测试时注入它。

public Task WhenCreateAsyncCalledSomePropertyIsSet() {
    // Arrange
    var mockSomeContext = new Mock<ISomeContext>();
    mockSomeContext
        .Setup(x => x.SaveChangesAsync())
        .ReturnsAsync(1); //Because the method under test is async

    var sut = new SomeService (mockSomeContext.Object); //Actual service, fake context
    var someObject = new SomeObject(); //actual object

    Assert.IsNull(someObject.SomeProperty); //making sure it was null to begin with

    // Act
    await sut.CreateAsync(someObject); //call method under test.
    var actual = someObject.SomeProperty; //get the value

    // Assert
    Assert.NotNull(actual); //Assert that it was actually set.
}

您的真实上下文将来自 abstraction/interface 或由提供该功能的东西包装。

复习 Moq Quickstart 以更好地了解框架。