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

时间:2017-06-08 18:42:26

标签: c# unit-testing moq xunit.net

我试图使用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)时设置SomeProperty参数的someObject属性。我的测试失败了..

更新:

我试图测试以下方法:

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(如上所述)。如果我忘了设置它,我希望测试失败。

1 个答案:

答案 0 :(得分:1)

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

摘要背景。

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

该类将重构,以便它不再依赖于实现问题并允许更大的灵活性。

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.
}

您的真实上下文将从抽象/接口派生,或由提供该功能的内容包装。

审核Moq Quickstart以更好地了解该框架。