Throws

The Throws method is used to throw an exception when a given call is made. This topic goes through a number of scenarios where the Throws method is useful.

Here is the system under test for these examples:

public interface IFoo 
{ 
    string Execute(string myStr); 
} 
Public Interface IFoo 
    Function Execute(ByVal str As String) 
End Interface 

Throw Exception on Method Call

Change a method behavior to throw an exception once it is called.

[TestMethod] 
[ExpectedException(typeof(ArgumentException))] 
public void ShouldThrowExceptionOnMethodCall() 
{ 
    // Arrange 
    var foo = Mock.Create<IFoo>(); 
 
    Mock.Arrange(() => foo.Execute(string.Empty)).Throws<ArgumentException>(); 
 
    // Act 
    foo.Execute(string.Empty); 
} 
<TestMethod()> 
<ExpectedException(GetType(ArgumentException))> 
Public Sub ShouldThrowExceptionOnMethodCall() 
    ' Arrange 
    Dim foo = Mock.Create(Of IFoo)() 
 
    Mock.Arrange(Function() foo.Execute(String.Empty)).Throws(Of ArgumentException)() 
 
    ' Act 
    foo.Execute(String.Empty) 
End Sub 

The assert step is done via the ExpectedException attribute, where we explicitly specify that an exception of type ArgumentException must be thrown during the execution of the test.

Throw Exception with Arguments on Method Call

Change a method behavior to throw an exception once it is called and pass arguments to the exception.

[TestMethod] 
[ExpectedException(typeof(ArgumentException))] 
public void ShouldThrowExceptionWithArgumentsOnMethodCall() 
{ 
    // Arrange 
    var foo = Mock.Create<IFoo>(); 
 
    Mock.Arrange(() => foo.Execute(string.Empty)).Throws<ArgumentException>("Argument shouldn't be empty."); 
 
    // Act 
    foo.Execute(string.Empty); 
} 
<TestMethod()> 
<ExpectedException(GetType(ArgumentException))> 
Public Sub ShouldThrowExceptionWithArgumentsOnMethodCall() 
    ' Arrange 
    Dim foo = Mock.Create(Of IFoo)() 
 
    Mock.Arrange(Function() foo.Execute(String.Empty)).Throws(Of ArgumentException)("Argument shouldn't be empty.") 
 
    ' Act 
    foo.Execute(String.Empty) 
End Sub 

The assert step is done via the ExpectedException attribute, where we explicitly specify that an exception of type ArgumentException must be thrown during the execution of the test. Calling foo.Execute with empty string will result in throwing an exception and passing "Argument shouldn't be empty." to it.

See Also

In this article
Not finding the help you need? Improve this article