or
I use FluentAssertions: [Fact] public void Exception_gets_thrown() { var foo = new Foo("validArgument"); foo.Invoking(f => f.Bar(null)) // null is an invalid argument .ShouldThrow<ArgumentNullException>(); }
But how to test if an exception gets thrown in the constructor. I just did it like this, but is there maybe a more appropriate way via FluentAssertions?
[Fact] public void Constructor_throws_Exception() { Action a = () => new Foo(null); // null is an invalid argument a.ShouldThrow<ArgumentNullException>(); }
public void AddKeys(bool resultIsValid) { if (!resultIsValid) { LogMyException(message); } }
public void Test() { var called = false; // Initialize test class Mock.NonPublic.Arrange(confStringManager, "LogMyException", ArgExpr.IsAny<string>()).DoInstead(() => called = true);// Do something which makes the class call LogMyExceptionAssert.True(called); }
Mock.Initialize<List<ListExtensions>>()
Mock.SetupStatic(
typeof
(ListExtensions));
Mock.Partial<List<IDataItem>>().For(x => x.RandomItem());
var resource = Mock.Create<LocalResource>();
Mock.Arrange(() => RoleEnvironment.GetLocalResource(
"workingfolder"
)).Returns(resource);
var context = Mock.Create<
MyDataContext
>();
var repository = new CustomerRepository(context);
var customer = new Customer
{
CustomerId = 0,
CompanyId = 1,
CustomerNo = "FAKE4",
FullName = "Isaac Fake4",
LastName = "Fake",
FirstName = "Isaac",
Sex = "M",
Birthdate = new DateTime(2000, 12, 1),
IsRecordActive = true,
IsRecordDeleted = false,
ModifiedOn = DateTime.Now,
ModifiedBy = "System.User"
};
Mock.Arrange(context.SubmitChanges).DoInstead(() =>
{ customer.CustomerId = 5; });
//Act
var actual = repository.Add(customer);
//Assert
Assert.AreEqual(5, actual.CustomerId);
public Customer Add(Customer customer)
{
this.context.Customer.InsertOnSubmit(customer);
this.context.SubmitChanges();
return customer;
}
Mock.SetupStatic(
typeof
(PageManager), StaticConstructor.NonMocked);
var pageManager = Mock.Create<PageManager>(Constructor.Mocked);
Mock.Initialize<PageService>();
var service = Mock.Create<PageService>();
Mock.Arrange(() => service.FirstCall()).CallOriginal();
Mock.Arrange(() => service.SecondCall()).returns(
null
);
service.FirstCall();
internal
class
InternalClass
{
public
int
GetInt() {
return
5; }
}
internal
class
InternalOwner
{
public
int
GetInt() {
return
5; }
public
InternalClass InternalClassField =
new
InternalClass();
public
InternalClass InternalClassProp
{
get
{
return
InternalClassField; }
}
}
...
[Test]
public
void
Test5()
{
InternalOwner io = Mock.Create<InternalOwner>();
// Mock.Arrange(() => io.GetInt()).Returns(6); // Test1, works.
// Mock.Arrange(() => io.InternalClassField.GetInt()).Returns(6); // Test2, works.
Mock.Arrange(() => io.InternalClassProp.GetInt()).Returns(6);
// Test3, FAILS.
}