Skip to content

Commit ea49dd1

Browse files
authored
throw exceptions (#21)
Co-authored-by: Ben Wesson <[email protected]>
1 parent be2e744 commit ea49dd1

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

DbMocker.Tests/DatabaseCommandTests.cs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,5 +379,48 @@ public void Mock_ExecuteDataset_WithFunction_Test()
379379

380380
}
381381

382+
[TestMethod]
383+
public void Mock_ThrowException_Test()
384+
{
385+
var conn = new MockDbConnection();
386+
387+
conn.Mocks
388+
.WhenAny()
389+
.Throws(new Exception("TestException"));
390+
391+
using (var cmd = new DatabaseCommand(conn))
392+
{
393+
var exception = Assert.ThrowsException<Exception>(() =>
394+
{
395+
cmd.CommandText.AppendLine("SELECT ...");
396+
cmd.ExecuteScalar<int>();
397+
});
398+
399+
Assert.IsNotNull(exception);
400+
Assert.AreEqual("TestException", exception.Message);
401+
}
402+
}
403+
404+
[TestMethod]
405+
public void Mock_ThrowGenericException_Test()
406+
{
407+
var conn = new MockDbConnection();
408+
409+
conn.Mocks
410+
.WhenAny()
411+
.Throws<Exception>();
412+
413+
using (var cmd = new DatabaseCommand(conn))
414+
{
415+
var exception = Assert.ThrowsException<Exception>(() =>
416+
{
417+
cmd.CommandText.AppendLine("SELECT ...");
418+
cmd.ExecuteScalar<int>();
419+
});
420+
421+
Assert.IsNotNull(exception);
422+
}
423+
}
424+
382425
}
383426
}

DbMocker/MockReturns.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,24 @@ public void ReturnsRow(MockTable returns)
114114
ReturnsFunction = (cmd) => new[] { returns };
115115
}
116116

117+
/// <summary>
118+
/// Throws the specified exception.
119+
/// </summary>
120+
/// <param name="exception">The exception.</param>
121+
public void Throws(Exception exception)
122+
{
123+
ReturnsFunction = command => throw exception;
124+
}
125+
126+
/// <summary>
127+
/// Throws the specified exception type.
128+
/// </summary>
129+
/// <typeparam name="TException">The type of the exception.</typeparam>
130+
public void Throws<TException>() where TException : Exception, new()
131+
{
132+
ReturnsFunction = command => throw new TException();
133+
}
134+
117135
/// <summary>
118136
/// Set output value for dbParameter, when the condition occured.
119137
/// </summary>

0 commit comments

Comments
 (0)