我正在使用SpecFlow,我想写一个如下的场景:
Scenario: Pressing add with an empty stack throws an exception
    Given I have entered nothing into the calculator
    When I press add
    Then it should throw an exception
这calculator.Add()将是一个例外,所以如何在标记的方法中处理这个[Then]?
我认为这两个测试的行为应该完全相同,事实上我已经使用MS Test在我的项目中编写了测试,现在却发现它不像NUnit那样尊重预期的消息.
NUnit(失败):
[Test, ExpectedException(typeof(System.FormatException), ExpectedMessage = "blah")]
public void Validate()
{
    int.Parse("dfd");
}
MS测试(通过):
[TestMethod, ExpectedException(typeof(System.FormatException), "blah")]
public void Validate()
{
    int.Parse("dfd");
}
无论我给ms测试什么消息,它都会通过.
如果消息不正确,有没有办法让ms测试失败?我甚至可以创建自己的异常属性吗?我宁愿不必为发生这种情况的每个测试编写一个try catch块.
我正在尝试使用a中的ExpectedException属性C# UnitTest,但我遇到问题让它与我的特定工作Exception.这是我得到的:
注意:我在线路周围包裹了星号,这给我带来了麻烦.
    [ExpectedException(typeof(Exception))]
    public void TestSetCellContentsTwo()
    {
        // Create a new Spreadsheet instance for this test:
        SpreadSheet = new Spreadsheet();
        // If name is null then an InvalidNameException should be thrown. Assert that the correct 
        // exception was thrown.
        ReturnVal = SpreadSheet.SetCellContents(null, "String Text");
        **Assert.IsTrue(ReturnVal is InvalidNameException);**
        // If text is null then an ArgumentNullException should be thrown. Assert that the correct
        // exception was thrown.
        ReturnVal = SpreadSheet.SetCellContents("A1", (String) null);
        Assert.IsTrue(ReturnVal …我已经使用ExpectedException功能设置了一些JUnit(4.12)测试,我希望测试在预期的异常之后继续.但是我从来没有看到日志'3',因为执行似乎在异常后停止,如果捕获事件?
这实际上是可能的,怎么样?
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testUserAlreadyExists() throws Exception {
    log.info("1");
    // Create some users
    userService.createUser("toto1");
    userService.createUser("toto2");
    userService.createUser("toto3");
    Assert.assertTrue( userService.userExists("toto1") );
    Assert.assertTrue( userService.userExists("toto2") );
    Assert.assertTrue( userService.userExists("toto3") );
    log.info("2");
    // Try to create an existing user
    exception.expect(AlreadyExistsException.class);
    userService.createUser("toto1");
    log.info("3");
}
我在测试中有一个奇怪的行为,我想测试当作为参数传入null时抛出异常.当我运行测试时,我从NUnit获得:
    System.ArgumentNullException was expected
    -- Exception doesn't have a stack trace -- 
我的测试:
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void Should_not_retrieve_any_fields_when_file_is_null()
{
    _creator.CreateFields(null);
}
我的实施:
public IEnumerable<ImportField> CreateFields(HttpPostedFileBase file)
{
    if (file == null) throw new ArgumentNullException("file");
    using (var reader = new StreamReader(file.InputStream))
    {
        var firstLine = reader.ReadLine();
        var columns = firstLine.Split(new[] { ',' });
        for (var i = 0; i < columns.Length; i++)
        {
            yield return new ImportField(columns[i], i);
        }
    }
}
这种行为是否有合理的解释,我应该以不同的方式实现我的实现吗?
我需要为下一个函数编写一个单元测试,我看到我可以使用[ExpectedException]
这是要测试的功能.
public static T FailIfEnumIsNotDefined<T>(this T enumValue, string message = null)
        where T:struct
    {
        var enumType = typeof (T);
        if (!enumType.IsEnum)
        {
            throw new ArgumentOutOfRangeException(string.Format("Type {0} is not an Enum, therefore it cannot be checked if it is Defined not have defined.", enumType.FullName));
        } 
        else if (!Enum.IsDefined(enumType, enumValue))
        {
            throw new ArgumentOutOfRangeException(string.Format("{1} Value {0} is not does not have defined value in Enum of type {0}. It should not be...", enumType.FullName, message ?? ""));
        }
        return enumValue;
    }
这里将使用代码来测试应该抛出的异常 …
是否在jUnit中等效于NUnit的ExpectedException或Assert.Throws <>?
我有几个这种模式的单元测试:
[TestMethod ()]
[ExpectedException (typeof (ArgumentNullException))]
public void DoStuffTest_Exception ()
{
    var foo = new Foo ();
    Foo.DoStuff (null);
}
事实证明,代码覆盖率将抛出线标记为半运行,因此每次我得到1块未覆盖的代码.
在考虑了这个问题一段时间后,我能想出的最佳解决方案是添加一个try/catch.由于这是一个重复的模式,我将创建一个帮助方法
public static void ExpectException<_T> (Action action) where _T: Exception
{
    try { action(); }
    catch (_T) { return; }
    Assert.Fail ("Expected " + _T);
}
这将有很好的附带好处,我可以将所有异常测试添加到非投掷测试.
这是一个有效的设计,还是我错过了什么?
编辑: Ugs ...看起来像上面的ExpectException方法也留下了1个未覆盖的块.
对junit的ExpectedException规则的使用有疑问:
正如这里建议的那样:junit ExpectedException 从junit 4.7开始的规则可以测试这样的异常(这比@Test(expected = Exception.class)要好得多):
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testFailuresOfClass() {
 Foo foo = new Foo();
 exception.expect(Exception.class);
 foo.doStuff();
}
现在我需要在一个测试方法中测试几个异常,并在运行以下测试后得到一个绿色条,因此认为每个测试都通过了.
@Test
public void testFailuresOfClass() {
 Foo foo = new Foo();
 exception.expect(IndexOutOfBoundsException.class);
 foo.doStuff();
 //this is not tested anymore and if the first passes everything looks fine
 exception.expect(NullPointerException.class);
 foo.doStuff(null);
 exception.expect(MyOwnException.class);
 foo.doStuff(null,"");
 exception.expect(DomainException.class);
 foo.doOtherStuff();
}
但是过了一会儿,我意识到第一次检查通过后,测试方法就会退出.至少可以说这是模棱两可的.在junit 3中这很容易实现......所以这是我的问题:
如何使用ExpectedException规则在一个测试中测试多个异常?
我正在努力ExpectedExceptions为JUnit 工作.我已经尝试了这个:
public class ExpectedTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();
    @Test
    public void test() {
        thrown.expect(NullPointerException.class);
        throw new NullPointerException();
    }
}
这引起了我以下异常:
java.lang.NoClassDefFoundError:org/hamcrest/TypeSafeMatcher,位于java.security.ClassLoader.defineClass(ClassLoader.java:800)的java.lang.ClassLoader.defineClass1(Native Method),位于java.security.SecureClassLoader.defineClass(SecureClassLoader.java) :142)java.net.URLClassLoader.accessClass(URLClassLoader.java:449)java.net.URLClassLoader.access $ 100(URLClassLoader.java:71)java.net.URLClassLoader $ 1.run(URLClassLoader.java:361)在java.net.URLClassLoader $ 1.run(URLClassLoader.java:355)java.security.AccessController.doPrivileged(Native Method),java.net.URLClassLoader.findClass(URLClassLoader.java:354),位于java.lang.ClassLoader.位于org.junit.matchers.JUnitMatchers.isThrowable的java.lang.ClassLoader.loadClass(ClassLoader.java:358)sun.misc.Launcher $ AppClassLoader.loadClass(Launcher.java:309)的loadClass(ClassLoader.java:425) (JUnitMatchers.java:103)在org.junit.rules.ExpectedException的org.junit.rules.ExpectedExceptionMatcherBuilder.build(ExpectedExceptionMatcherBuilder.java:27).handleOception(ExpectedException.java:198)org.junit.rules.ExpectedException.access $ 500(ExpectedException.java:85)org.junit.rules.ExpectedException $ ExpectedExceptionStatement.evaluate(ExpectedException.java:177)org.junit.在org.junit的org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)的org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)上的rules.RunRules.evaluate(RunRules.java:20) .runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:238)at org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:63)at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:53)org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java: 229)在org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)的org.junit.runners.ParentRunner.run(ParentRunner.java:309)在org.eclipse上的org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)位于org.eclipse.jdt.internal的org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)的.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) .junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)由java.net中的java.net.URLClassLoader $ 1.run(URLClassLoader.java:366)引起的java.lang.ClassNotFoundException:org.hamcrest.TypeSafeMatcher. URLClassLoader $ 1.run(URLClassLoader.java:355)在java.security.AccessController.doPrivileged(Native Method)java.net.URLClassLoader.findClass(URLClassLoader.java:354)java.lang.ClassLoader.loadClass(ClassLoader.java) :425)at sun.misc.Launcher $ AppClassLoader.loadClass(Launcher.java:308)at java.lang.ClassLoader.loadClass(ClassLoader.java:358)... 33更多
当我这样做时:
public class ExpectedTest {
    @Rule
    public ExpectedException thrown;
    @Before
    public void …unit-testing ×6
c# ×5
java ×3
junit4 ×3
nunit ×3
junit ×2
testing ×2
assertions ×1
exception ×1
hamcrest ×1
junit-rule ×1
mstest ×1
specflow ×1
yield ×1