标签: assert

公共方法中的前置条件和后置条件检查

我正在阅读有关使用关键字验证方法前置条件和后置条件的Oracle 文档。assert

该文档说,可以使用assert关键字来验证public方法的后置条件,但您应该只使用assert关键字来验证private方法的前置条件。

为什么是这样?

java assert preconditions post-conditions

3
推荐指数
1
解决办法
1608
查看次数

使用 Task.Run 内部调用的 Moq 方法进行单元测试

我正在尝试在我想要测试的方法内模拟服务调用。

方法体如下所示:

public string OnActionException(HttpActionContext httpRequest, Exception ex)
{
    var formattedActionException = ActionLevelExceptionManager.GetActionExceptionMessage(httpRequest);

    var mainErrorMessage = $"[{formattedActionException.ErrorId}]{formattedActionException.ErrorMessage}, {ex.Message}";

    this.LogError(mainErrorMessage, ex);

    if (this._configuration.MailSupportOnException)
        Task.Run(async () => await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $"{mainErrorMessage} ---> Stack trace: {ex.StackTrace.ToString()}")); 

    return $"(ErrID:{formattedActionException.ErrorId}) {formattedActionException.ErrorMessage} {formattedActionException.KindMessage}";
}
Run Code Online (Sandbox Code Playgroud)

我在测试中试图模拟的是:

Task.Run(async () => 等待 this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $"{mainErrorMessage} ---> 堆栈跟踪: {ex.StackTrace.ToString()}"));

测试方法如下所示:

[TestMethod]
public void We_Send_System_Exception_On_Email_If_Configured_In_Settings()
{
    // arrange
    this._configurationWrapperMock.Setup(cwm => cwm.MailSupportOnException)
        .Returns(true);
    this._mailServiceMock.Setup(msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()))
        .Returns(Task.FromResult(0));

    // act
    var logger = new ApiLogger(this._configurationWrapperMock.Object, this._mailServiceMock.Object);
    logger.OnActionException(
        new HttpActionContext(
            new HttpControllerContext()
            {
                Request = …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing assert moq mocking

3
推荐指数
1
解决办法
9249
查看次数

cucumber.js 并且不是一个函数

我正在练习使用 cucmber.js 通过 BDD 编写一些单元测试。当我尝试使用“And”语句时。该错误表明

TypeError: And is not a function
Run Code Online (Sandbox Code Playgroud)

这是我的代码

。特征

Feature: dataTable
Scenario Outline: <a> + <b> + <c> = <answer>
  Given I had number <a>
    And I add another number <b>
  When I add with <c>   
  Then I got answer <answer>

Examples:
|a|b|c|answer|
|1|2|3|6|
|10|15|25|50|
Run Code Online (Sandbox Code Playgroud)

.stepDefinition

defineSupportCode(function({Given,When,Then,And}){
  let ans = 0;
  Given('I had number {int}', function(input){
    ans = input
  })
  And('I add another number {int}',function(input){
    ans += input
  })
  When('I add with {int}',function(input){
    ans += input …
Run Code Online (Sandbox Code Playgroud)

javascript bdd assert cucumber

3
推荐指数
1
解决办法
4506
查看次数

为什么 Lua 中的 error() 比 assert() 运行得更快?

条件断言是以策略方式设计应用程序的众所周知的方法。您可以完全确定您的代码在发布后一天能够正常工作,而且当您团队中的其他开发人员更改此代码时也是如此。

在 Lua 代码中放置断言有两种常见方法:

assert(1 > 0, "Assert that math works")
Run Code Online (Sandbox Code Playgroud)
if 1 <= 0 then
    error("Assert that math doesn't work")
end
Run Code Online (Sandbox Code Playgroud)

从性能的角度来看,我希望这件事类似。仅考虑风格问题。但事实并非如此。

断言在我的机器上工作时间更长:

function with_assert()
    for i=1,100000 do 
        assert(1 < 0, 'Assert')
    end
end

function with_error()
    for i=1,100000 do 
        if 1 > 0 then
            error('Error')
        end
    end
end

local t = os.clock()
pcall(with_assert)
print(os.clock() - t)

t = os.clock()
pcall(with_error)
print(os.clock() - t)
Run Code Online (Sandbox Code Playgroud)

>> 3.1999999999999e-05

>> 1.5e-05

为什么会发生这种情况?

performance lua assert

3
推荐指数
1
解决办法
3290
查看次数

与 if-else 条件相比,使用 if any 断言有什么优势?

例如 x =“你好”。我可以不做 if x != "hello" 而不是执行 assert x == "hello" 吗?使用断言更Pythonic吗?

python assert

3
推荐指数
1
解决办法
4190
查看次数

Groovy - 类型测试?

我真的是Groovy的新手,我正在努力完成任务.我写了一些Groovy代码(效果很好),它接收一些文本.此文本应为整数(介于0和10之间).用户可能会输入不同的内容.在那种情况下,我想做一些特定的错误处理.

现在我想知道,如果字符串类型变量可以转换为整数,那么测试最好/最常用的方法是什么?

(我想要做的是消耗字符串中的整数或将计算结果设置为0.

谢谢!

testing grails groovy assert integer

2
推荐指数
1
解决办法
2814
查看次数

适当使用断言

能帮助我更好地理解,"断言"与"抛出异常"的适当用法是什么?每个场景何时适用?

场景1

public Context(Algorythm algo) {
  if (algo == null) {
      throw new IllegalArgumentException("Failed to initialize Context");
  }
  this.algo = algo;
}
Run Code Online (Sandbox Code Playgroud)

测试

public void testContext_null() {
  try {
      context = new Context(null);
      fail();
  } catch (IllegalArgumentException e) {
      assertNotNull(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

情景2

public Context(Algorythm algo) {
  assert (algo != null);
  this.algo = algo;
}
Run Code Online (Sandbox Code Playgroud)

测试

public void testContext_null() {
  try {
      context = new Context(null);
      fail();
  } catch (AssertionFailedError e) {
      assertNotNull(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

java junit assert

2
推荐指数
1
解决办法
2467
查看次数

如何在unittest中测试ok中的异常

我有关于unittest的问题.如何进行测试以查看是否存在异常?一个例子:

基准(3,32,2012)

如果我像这样调用类Datum,其中月份不在范围内(> 31),它就是一切正常,它会抛出异常并且没关系.但是如果Exception正常,我想做一个单元测试,如果正在捕获异常确定..?我做了一些测试,但这些只有True值,而且没关系.我不知道如何以这种方式进行测试..并在互联网上搜索..感谢您的回复.

import date,datetime

class Datum():
    def __init__(self,day,month,year):
        try:
            d=int(day)
            dvm=stevilodnivmesecu(month,year)
            if (d>=1 and d<=dvm):
                self.d=d
            else:
                raise Exception("Day out of moth range")
        except:
            raise ValueError("Day is not a number")
        try:
            m=int(month)
            if m>=1 and m<=12:
                self.m=m
            else:
                raise Exception("Month out of range")
        except:
            raise ValueError("Month is not a number")
        try:
            l=int(year)
            if l>=1000 and l<=9999:
                self.l=l
            else:
                raise Exception("Year is out of range")
        except:
            raise ValueError("Year is not a number")

    def __repr__(self):
        return repr(self.d)+"."+repr(self.m)+"."+repr(self.l)

def monthrange(month,year):
    if …
Run Code Online (Sandbox Code Playgroud)

python testing unit-testing assert

2
推荐指数
1
解决办法
191
查看次数

断言私有方法的例外

我使用NUnit对C#中的私有方法进行单元测试.

例如,我的方法(如果是公共的)应该抛出一个ArgumentNullException.我可以声明该方法抛出ArgumentNullException如此:Assert.Throws<ArgumentNullException>(() => method.Call());

但是,因为我使用反射调用私有方法,所以我会断言一个TargetInvocationException抛出ArgumentNullException类似的方法:Assert.Throws<TargetInvocationException>(() => methodInfo.Invoke(obj, new object[] { params }));

我想声明一个ArgumentNullException而不是一个TargetInvocationException私有方法,所以我可以扫描它的代码,知道它的预期做什么而不是调试找出来.

我如何断言实际的异常,而不是TargetInvocationException

注意:这个问题并没有解决单元测试公共与私有方法背后的理论.我和我的团队决定对私有方法进行单元测试,这是否是单元测试的方式与这个问题无关.请参阅问题上最受欢迎的答案,以了解我们的理由.

c# nunit assert exception private-methods

2
推荐指数
1
解决办法
1910
查看次数

如何在不更改命令行的情况下禁用断言?

我有带有断言的C++代码.当我用g++ -D NDEBUG选项编译代码时,没有执行断言命令.但是当我在代码中包含NDEBUG #define NDEBUG并且没有-D NDEBUG选项编译它时,执行assert命令.如何在不更改命令行的情况下禁用断言?

c++ debugging assert

2
推荐指数
1
解决办法
2503
查看次数