标签: expected-exception

ExpectedExceptionAttribute在MSTest中不起作用

这很奇怪,但前ExpectedExceptionAttribute几天突然停止为我工作.不确定出了什么问题.我正在和VS 2010和VS 2005并排运行.它在VS 2010中不起作用.这个测试应该通过,但它失败了:

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Exception()
{
    throw new ArgumentNullException("test");
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?这真的是sux.

c# unit-testing mstest visual-studio-2010 expected-exception

6
推荐指数
2
解决办法
2603
查看次数

grails单元测试中的@ExpectedException

有人在grails单元测试中使用过这个注释吗?似乎没有为我工作.谢谢.d

更新:我下面测试的最后一行确实抛出了预期的异常.但是测试失败了(这里的堆栈跟踪太大......).我正在使用grails 1.2并在eclipse的junit runner中运行测试.也许grails使用的是早期版本的junit而不是4?

/**
 * Get the EC by a manager of a different company. Should throw exception
 */
@ExpectedException(ServiceAuthorizationException.class)
void testGetEcByNonOwnerManagerOfDifferentCompany() {
    mockDomain(ExpenseClaim , [new ExpenseClaim(id:"1",narrative:"marksClaim", employee:userMark, company:dereksCompany)])      

    def authControl = mockFor(AuthenticateService)
    authControl.demand.userDomain(1..1)  {-> otherUserMgr }
    authControl.demand.ifAllGranted(1..1)  {String arg1 -> return "ROLE_COMPANYMANAGER".equals(arg1) } //returns true
    def testService = new ExpenseClaimService()
    testService.authenticateService = authControl.createMock()
    def thrown = false
    testService.getExpenseClaim("1")
}
Run Code Online (Sandbox Code Playgroud)

grails unit-testing expected-exception

6
推荐指数
1
解决办法
5369
查看次数

ExpectedException原因的原因?

我正在尝试验证我的所有异常都是正确的.因为值被包装CompletableFutures,抛出ExecutionException的异常是因为我通常会检查的异常.快速举例:

void foo() throws A {
  try {
    bar();
  } catch B b {
    throw new A(b);
  }
}
Run Code Online (Sandbox Code Playgroud)

所以foo()转换异常由抛出bar(),而所有这一切都内部完成CompletableFuturesAsyncHandlers(我不会复制整个代码,它只是供参考)

在我的单元测试中,我正在bar()抛出一个异常,并希望在调用时检查它是否正确转换foo():

Throwable b = B("bleh");
when(mock.bar()).thenThrow(b);
ExpectedException thrown = ExpectedException.none();
thrown.expect(ExecutionException.class);
thrown.expectCause(Matchers.allOf(
                instanceOf(A.class),
                having(on(A.class).getMessage(),
                        CoreMatchers.is("some message here")),
        ));
Run Code Online (Sandbox Code Playgroud)

到目前为止这么好,但我也想验证A异常的原因是异常Bhaving(on(A.class).getCause(), CoreMatchers.is(b))原因CodeGenerationException --> StackOverflowError

TL; DR:我如何得到预期异常的原因?

java junit exception-handling hamcrest expected-exception

6
推荐指数
1
解决办法
2139
查看次数

Android 发布错误:需要一个颜色资源 ID (R.color.) 但收到一个 RGB 整数

我在市场上有一年的应用程序。上周,我更改了我的应用程序的源代码。当我想构建发布版本时,Android Studio 会抛出一个错误:

“错误:需要一个颜色资源 ID (R.color.),但收到一个 RGB 整数 [ResourceType]”

颜色只用在这部分代码中,我没有在这部分做任何改变:

if (android.os.Build.VERSION.SDK_INT >= 16) {
            rlFlash.setBackground(new ColorDrawable
                    (Color.parseColor(("#86cc55"))));
        }
        else{
            rlFlash.setBackgroundDrawable(new ColorDrawable
                    (Color.parseColor(("#86cc55"))));
        }
Run Code Online (Sandbox Code Playgroud)

很奇怪,在 Debug 版本中 Android studio 没有抛出任何错误,我可以构建 apk。

你知道怎么回事吗??

谢谢。

android colors expected-exception r.java-file

5
推荐指数
1
解决办法
4698
查看次数

如何在C++/CLI NUnit测试中使用ExpectedException?

你怎么做相当于:

[Test, ExpectedException( typeof(ArgumentOutOfRangeException) )]
void Test_Something_That_Throws_Exception()
{
    throw gcnew ArgumentOutOfRangeException("Some more detail");
}
Run Code Online (Sandbox Code Playgroud)

...在C++中(有C#的例子)?据我所知,NUnit的C++实现没有typeof()函数.

testing nunit c++-cli exception expected-exception

4
推荐指数
1
解决办法
1137
查看次数

MS单元测试中的例外情况?

我为我的项目方法创建了一个单元测试.当找不到文件时,该方法引发异常.我为此编写了一个单元测试,但是在引发异常时我仍然无法通过测试.

方法是

public string[] GetBuildMachineNames(string path)
{
    string[] machineNames = null;

    XDocument doc = XDocument.Load(path);

    foreach (XElement child in doc.Root.Elements("buildMachines"))
    {
        int i = 0;
        XAttribute attribute = child.Attribute("machine");
        machineNames[i] = attribute.Value;
    }
    return machineNames;
}
Run Code Online (Sandbox Code Playgroud)

单元测试

[TestMethod]
[DeploymentItem("TestData\\BuildMachineNoNames.xml")]
[ExpectedException(typeof(FileNotFoundException),"Raise exception when file not found")]
public void VerifyBuildMachineNamesIfFileNotPresent()
{
    var configReaderNoFile = new ConfigReader();
    var names = configReaderNoFile.GetBuildMachineNames("BuildMachineNoNames.xml");
}
Run Code Online (Sandbox Code Playgroud)

我应该处理方法中的异常还是我错过了其他的东西?

编辑:

我传递的路径不是找到文件的路径,所以这个测试应该通过...即如果文件不存在于该路径中该怎么办.

c# unit-testing expected-exception

4
推荐指数
1
解决办法
4231
查看次数

使用 pytest 和假设进行异常处理和测试

我正在编写带有假设的统计分析测试。ZeroDivisionError当传递非常稀疏的数据时,假设导致我在代码中出现 a 。所以我调整了我的代码来处理异常;就我而言,这意味着记录原因并重​​新引发异常。

try:
    val = calc(data)
except ZeroDivisionError:
    logger.error(f"check data: {data}, too sparse")
    raise
Run Code Online (Sandbox Code Playgroud)

我需要通过调用堆栈向上传递异常,因为顶级调用者需要知道存在异常,以便它可以将错误代码传递给外部调用者(REST API 请求)。

编辑:我也无法为val;分配合理的值 本质上我需要一个直方图,当我根据数据计算合理的箱宽度时会发生这种情况。显然,当数据稀疏时,这会失败。如果没有直方图,算法就无法继续进行。

现在我的问题是,在我的测试中,当我做这样的事情时:

@given(dataframe)
def test_my_calc(df):
    # code that executes the above code path
Run Code Online (Sandbox Code Playgroud)

hypothesis不断生成触发的失败示例ZeroDivisionError,并且我不知道如何忽略此异常。通常我会用 标记这样的测试pytest.mark.xfail(raises=ZeroDivisionError),但在这里我不能这样做,因为相同的测试可以通过良好的输入。

像这样的东西是理想的:

  1. 但是,对大多数输入照常继续测试
  2. ZeroDivisionError引发时,将其视为预期失败而跳过。

我怎样才能做到这一点?我还需要try: ... except: ...在测试主体中放入 a 吗?我需要在 except 块中做什么才能将其标记为预期失败?

编辑:为了解决@hoefling的评论,分离出失败的案例将是理想的解决方案。但不幸的是,hypothesis没有给我足够的句柄来控制它。我最多可以控制生成数据的总数和限制(最小值,最大值)。然而,失败案例的范围非常窄。我没有办法控制这一点。我想这就是假设的要点,也许我根本不应该为此使用假设。

这是我生成数据的方式(稍微简化):

cities = [f"city{i}" for i in range(4)]
cats = [f"cat{i}" for i in range(4)]


@st.composite
def …
Run Code Online (Sandbox Code Playgroud)

python expected-exception pytest python-hypothesis

4
推荐指数
1
解决办法
1316
查看次数

奇怪的编译器错误,声明我的迭代器未定义

我正在尝试创建一个模板函数,它将迭代映射的指定键/值对,并检查是否存在函数参数中指定的任何键.

实现如下:

template < class Key, class Value >
bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key )
{
    std::map< Key, Value >::iterator it = map.lower_bound( key );
    bool keyExists = ( it != map.end && !( map.key_comp() ( key, it->first ) ) );
    if ( keyExists )
    {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

然而,无论出于何种原因,我似乎无法弄清楚为什么我的代码无法编译.我得到了这些错误:

error: expected ';' before 'it'
error: 'it' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

我之前碰到过这些,但这些通常都是由于我所犯的错误很容易发现.这可能会发生什么?

c++ scope compiler-errors expected-exception

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

如何表明我不希望 JUnit 出现异常?

在谷歌测试中,我们有一个

EXPECT_NO_THROW(x.foo());
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 JUnit 中做到这一点?我想避免的事情是必须编写一个try/catch块,并指定我的测试函数可以做throw任何事情。Java强制我throws用测试函数声明一个子句......

是否可以?

junit expected-exception

0
推荐指数
1
解决办法
3965
查看次数

C 中简单 for 循环中的预期标识符或 '('

我写函数,检查是字符串是否只包含字母。如果我n在循环外声明:

int n = strlen(str);
for (int i = 0; i < n; i++)
Run Code Online (Sandbox Code Playgroud)

它没有错误并且效果很好,但是如果我n在里面移动声明:

for (int i = 0, int n = strlen(str); i < n; i++)
Run Code Online (Sandbox Code Playgroud)

我有错误:

vigenere.c:71:21: error: expected identifier or '('
    for (int i = 0, int n = strlen(str); i < n; i++)
                    ^
vigenere.c:71:21: error: expected ';' in 'for' statement specifier
vigenere.c:71:21: error: expected expression
vigenere.c:71:46: error: use of undeclared identifier 'n'
    for (int i = 0, int n = …
Run Code Online (Sandbox Code Playgroud)

c for-loop compiler-errors expected-exception cs50

-1
推荐指数
1
解决办法
2963
查看次数

我在哪里修复关于模板的C++代码?

当我编写C++代码并通过clang ++编译器编译它时,

error: expected expression
template <typename T>
^
Run Code Online (Sandbox Code Playgroud)

有代表.

为什么会出现此错误,如何解决?

#include<iostream>
using namespace std;

int main() {

template <typename T>
T sum(T a, T b) {
return a+b;
}

cout <<"Sum = " << sum( 2.1, 7.9 ) << endl;

return 1;
}
Run Code Online (Sandbox Code Playgroud)

c++ templates expected-exception clang++

-5
推荐指数
1
解决办法
52
查看次数