简体   繁体   English

如何断言是否使用nunit调用了一个方法

[英]how to assert if a method has been called using nunit

is it possible to assert whether a method has been called? 是否可以断言是否已调用方法? I'm testing the following method and I want to assert that the _tokenManager.GetToken() has been called. 我正在测试以下方法,我想声明_tokenManager.GetToken()已被调用。 I just want to know if the method has been called as the method does not return a value. 我只是想知道方法是否已被调用,因为该方法不返回值。 I am using Moq. 我正在使用Moq。

Thanks, 谢谢,

Code snippet 代码段

public void Subscribe(string code, string emailAddress, string columnKey)
{
    // Request authentication token
    var token = _tokenManager.GetToken(code, false);

    if (!_tokenValidator.Validate(token))
    {
        // Token has expired or invalid - refresh the token 
        token = _tokenManager.GetToken(code, true);
    }

    // Subscribe email
    _silverpopRepository.Subscribe(token.AccessToken, emailAddress, columnKey);
}

You should mock TokenManager and TokenValidator , and then create two unit test cases: 您应该模拟TokenManagerTokenValidator ,然后创建两个单元测试用例:

  • Case 1: token is validated and GetToken is called exactly once 情况1: 验证令牌并且只调用一次GetToken
  • Case 2: token is not validated and GetToken is called exactly twice 情况2: 未验证令牌,并且两次调用GetToken

Case 1: 情况1:

[Test]
public void Subscribe_TokenIsValidated_GetTokenIsCalledOnce()
{
    // Arrange:
    var tokenManagerMock = Mock.Of<TokenManager>();

    var tokenValidatorMock = Mock.Of<TokenValidator>(x =>
        x.Validate(It.IsAny<Token>()) == true);

    var subscriber = new Subscriber
    {
        TokenManager = tokenManagerMock,
        TokenValidator = tokenValidatorMock
    };

    // Act:
    subscriber.Subscribe(It.IsAny<string>(), It.IsAny<string>(),
        It.IsAny<string>());

    // Assert:
    Mock.Get(tokenManagerMock).Verify(x =>
        x.GetToken(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
}

Case 2: 案例2:

[Test]
public void Subscribe_TokenIsExpiredOrInvalid_GetTokenIsCalledTwice()
{
    // Arrange:
    var tokenManagerMock = Mock.Of<TokenManager>();

    var tokenValidatorMock = Mock.Of<TokenValidator>(x =>
        x.Validate(It.IsAny<Token>()) == false);

    var subscriber = new Subscriber
    {
        TokenManager = tokenManagerMock,
        TokenValidator = tokenValidatorMock
    };

    // Act:
    subscriber.Subscribe(It.IsAny<string>(), It.IsAny<string>(),
        It.IsAny<string>());

    // Assert:
    Mock.Get(tokenManagerMock).Verify(x =>
        x.GetToken(It.IsAny<string>(), It.IsAny<bool>()), Times.Exactly(2));
}

Alternatively, you can create an unit test without mocking TokenValidator and verify if GetToken() has been called at least once. 或者,您可以在不TokenValidator情况下创建单元测试,并验证是否至少调用了一次GetToken() However, creating two cases as in the first example is preferred as we are testing all code paths. 但是,在第一个示例中创建两个案例是首选,因为我们正在测试所有代码路径。

// Arrange:
var tokenManagerMock = Mock.Of<TokenManager>();
var subscriber = new Subscriber {TokenManager = tokenManagerMock};

// Act:
subscriber.Subscribe(It.IsAny<string>(),
    It.IsAny<string>(),
    It.IsAny<string>());

// Assert:
Mock.Get(tokenManagerMock).Verify(x =>
        x.GetToken(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeastOnce);

Read more about verification in Moq at: 在Moq阅读更多关于验证的信息:

You can verify using MOQ using the Verify method. 您可以使用Verify方法使用MOQ进行验证。 Like this: 像这样:

var tokenManagerMock = new Mock<ITokenManager>();
var sut = new WhateverItIsCalled(tokenManagerMock.Object);
sut.Subscribe("ssss", "example@example.com", "XXX");
tokenManagerMock.Verify(m => m.GetToken(It.Is<string>(c => c == "ssss", It.Is<bool>(x => x == false)), Times.Once); 

You need to be able to pass the token manager into your system under test somehow. 您需要能够以某种方式将令牌管理器传递到您正在测试的系统中。 Usually via the ctor or maybe a property. 通常通过ctor或可能是财产。

I would suggest you use something like AutoFixture to remove the ugliness that is "ssss" and make things a bit more DRY. 我建议你使用像AutoFixture这样的东西来消除“ssss”的丑陋并使事情变得更加干燥。

You may need to make the token manager mock return something appropriate too that will pass the validation. 您可能需要使令牌管理器模拟返回适当的内容以通过验证。 Something like this: 像这样的东西:

var tokenManagerMock = new Mock<ITokenManager>();
tokenManagerMock.Setup(m => m.GetToken(It.Is<string>(x => x == "ssss", It.IsAny<bool>()).Returns("XXXXXX");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM