I have a custom assertion class that I'm currently unit testing.
public static class AssertionExtensions
{
public static void ShouldHaveAttributeApplied<T>(this T obj, Type attributeType)
{
Assert.IsNotNull(Attribute.GetCustomAttribute(typeof(T), attributeType));
}
}
The tests for this class are:
[TestMethod]
public void When_Called_For_Class_Validates_Pass_Correctly()
{
var obj = new FakeClass();
obj.ShouldHaveAttributeApplied(typeof(FakeClassAttribute));
}
[TestMethod]
public void When_Called_For_Class_Validates_Fail_Correctly()
{
var obj = new FakeClass();
obj.ShouldHaveAttributeApplied(typeof(UnappliedFakeClassAttribute));
}
The test When_Called_For_Class_Validates_Fail_Correctly fails as expected, but how do I mark this fail as a pass in the test suite?
This is using C# / MSTest.
Adding the ExpectedException attribute with the exception set to AssertionFailedException makes the test pass as intended.
Usage:
[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void When_Called_For_Class_Validates_Fail_Correctly()
{
var obj = new FakeClass();
obj.ShouldHaveAttributeApplied(typeof(UnappliedFakeClassAttribute));
}
Related
Why does this unit test not fail when no guard clause is present?
[Test]
public void ConstructorLooksGuardedAgainstNulls()
{
// ARRANGE
var fixture = new Fixture();
var assertion = fixture.Create<GuardClauseAssertion>();
// ACT & ASSERT
assertion.Verify(typeof(TestClass).GetConstructors(BindingFlags.Public));
}
Classes used in unit test:
public class TestBaseClass
{
private readonly string _firstDependency;
private readonly string _secondDependency;
protected TestBaseClass(string firstDependency, string secondDependency)
{
_firstDependency = firstDependency;
_secondDependency = secondDependency;
}
}
public class TestClass : TestBaseClass
{
public TestClass(string firstDependency)
: base(firstDependency, string.Empty)
{
}
}
I removed all the irrelevant lines.
This will return all public constructors, and then the test will fail as expected:
typeof(TestClass).GetConstructors()
The version with the BindingFlags parameter doesn't return the public constructors (although it reads like it really should do). Because no constructor are found, the test passes
typeof(TestClass).GetConstructors(BindingFlags.Public)
I have a class with a private method
public class MyClass
{
private void SomeMethod(PrimaryAllocationDP packet)
{
........................
some code
........................
packet.AllocatedAgency = AgencyAllocated;
}
}
Now by using MSUnit Testing framework, I have written so far
[TestMethod]
public void TestAllocatedAgency()
{
var packet = new Fixture().Create<PrimaryAllocationDP>(); //used AutoFixture here
PrivateObject accessor = new PrivateObject(new MyClass());
accessor.Invoke("SomeMethod", packet); //Act
// what will be the Assert? Since it is void
}
What will be the Assert? Since it is void, how can I write the assert?
Well given that in the example the method under test is making a change to its argument/dependency you could assert that the desired result of calling the function is that the packet's AllocatedAgency property is in fact not null
[TestMethod]
public void TestAllocatedAgency() {
//Arrange
var packet = new Fixture().Create<PrimaryAllocationDP>(); //used AutoFixture here
var sut = new MyClass();
var accessor = new PrivateObject(sut);
//Act
accessor.Invoke("SomeMethod", packet);
//Assert
Assert.IsNotNull(packet.AllocatedAgency);
}
If it is possible for you to change PrimaryAllocationDP you can also add a new interface IPrimaryAllocationDP and test the property setting. In my test I am assuming AllocatedAgency is of type object and I am using Moq. But maybe you can also use AutoFixture for mocking? To make it more clear I set AgencyAllocated directly in MyClass
[TestFixture]
public class DependencyInjection
{
[TestMethod]
public void TestAllocatedAgency()
{
var packet = new Mock<IPrimaryAllocationDP>();
PrivateObject accessor = new PrivateObject(new MyClass());
accessor.Invoke("SomeMethod", packet.Object); //Act
packet.VerifySet(p => p.AllocatedAgency = 42);
}
}
public interface IPrimaryAllocationDP
{
//object or any other type
object AllocatedAgency { set; }
}
public class PrimaryAllocationDP : IPrimaryAllocationDP
{
public object AllocatedAgency { set; private get; }
}
public class MyClass
{
private readonly object AgencyAllocated = 42;
private void SomeMethod(IPrimaryAllocationDP packet)
{
//........................
//some code
//........................
packet.AllocatedAgency = AgencyAllocated;
}
}
I am testing my class
public class myclass
{
private IAwesome awesomeObject;
public myclass(IAwesome awesomeObject)
{
this.awesomeObject = awesomeObject;
}
public void MethodUnderTest()
{
this.awesomeObject.RunSomething(); //I want to verify that RunSomething was called
}
}
The way I am doing this is:
//Arrange
var mockAwesome = new Mock<IAwesome>();
mockAwesome.Setup(x=>x.RunSomething()).Returns ... Verify()...;
//Act
var sut = new myclass(mockAwesome.object);
sut.MethodUnderTest();
//Assert
mockAwesome.Verify();
The exception I am getting is:
System.NotSupportedException : Expression references a method that
does not belong to the mocked object: x => x.RunSomething
Is it not possible to test that a specific method was executed on a mocked object that I passed into a class, that is now part of a private member of that class?
Modify set up line to mockAwesome.Setup(x=>x.RunSomething()).Verifiable() and it should work for the example you provided.
[TestClass]
public class MoqVerificationTest {
[TestMethod]
public void Moq_Should_Verify_Setup() {
//Arrange
var mockAwesome = new Mock<IAwesome>();
mockAwesome.Setup(x => x.RunSomething()).Verifiable();
//Act
var sut = new myclass(mockAwesome.Object);
sut.MethodUnderTest();
//Assert
mockAwesome.Verify();
}
public interface IAwesome {
void RunSomething();
}
public class myclass {
private IAwesome awesomeObject;
public myclass(IAwesome awesomeObject) {
this.awesomeObject = awesomeObject;
}
public void MethodUnderTest() {
this.awesomeObject.RunSomething(); //I want to verify that RunSomething was called
}
}
}
To confirm, comment out this.awesomeObject.RunSomething() in your sample class and run the test again. It will fail because you setup the RunSomething as Verifiable() and it was not used.
When testing, works perfectly fine for me...
Try this approach see if anything different results...
void Main()
{
IAwesome awesome = Mock.Of<IAwesome>();
Mock<IAwesome> mock = Mock.Get(awesome);
mock.Setup(m => m.RunSomething());
MyClass myClass = new MyClass(awesome);
myClass.MethodUnderTest();
mock.Verify(m => m.RunSomething(), Times.Once);
}
public interface IAwesome
{
void RunSomething();
}
public class MyClass
{
private IAwesome awesomeObject;
public myclass(IAwesome awesomeObject)
{
this.awesomeObject = awesomeObject;
}
public void MethodUnderTest()
{
this.awesomeObject.RunSomething();
}
}
So I am pretty new to webdriver and nunit, I am building out regression tests for my legacy products and have the need to run my tests in multiple browsers and I would like them to be configurable to different integration environments. I have the multiple browsers working but am unsure how to parameterize the test fixtures.
[TestFixture(typeof(FirefoxDriver))]
[TestFixture(typeof(ChromeDriver))]
[TestFixture(typeof(InternetExplorerDriver))]
public class UnitTest1<TWebDriver> where TWebDriver: IWebDriver, new()
{
PTGeneral General;
[TestFixtureSetUp]
public void SetUp()
{
General = new PTGeneral();
General.Driver = new TWebDriver();
}
I would just use the TestCaseSource attribute to specify the values to each test:
[TestFixture(typeof(FirefoxDriver))]
[TestFixture(typeof(ChromeDriver))]
[TestFixture(typeof(InternetExplorerDriver))]
public class UnitTest1<TWebDriver> where TWebDriver: IWebDriver, new()
{
// ...
public IEnumerable<string> UrlsToTest
{
get
{
yield return "http://www.example.com/1";
yield return "http://www.example.com/2";
yield return "http://www.example.com/3";
}
}
[TestCaseSource("UrlsToTest")]
public void Test1(string url)
{
// ...
}
[TestCaseSource("UrlsToTest")]
public void Test2(string url)
{
// ...
}
}
The most simple answer to your question is to use [TestCase] attributes for your test methods.
Use the next example:
[TestFixture("sendSomethingToConstructor")]
class TestClass
{
public TestClass(string parameter){}
[TestCase(123)] //for parameterized methods
public void TestMethod(int number){}
[Test] //for methods without parameters
public void TestMethodTwo(){}
[TearDown]//after each test run
public void CleanUp()
{
}
[SetUp] //before each test run
public void SetUp()
{
}
}
I'm writing a unit test to verify that the serializable attributes are set on my class. I thought I was on the right way, but for some reason I can't find the attribute types.
Here is my class:
[DataContract]
public class User
{
[DataMember]
public int Id { get; set; }
}
And a unit test for checking the attributes:
[Test]
public void DataMembersSetAsExpected()
{
var type = typeof(User);
Assert.That(type.IsDefined(typeof(System.Runtime.Serialization.DataContractAttribute), true));
var idProperty = type.GetProperty("Id");
Assert.That(idProperty.IsDefined(typeof(System.Runtime.Serialization.DataMemberAttribute), true));
}
The problem here is that the types of the attributes are unknown. Where can I find the right attribute definitions?
System.Runtime.Serialization.DataContractAttribute
System.Runtime.Serialization.DataMemberAttribute
Add a reference to System.Runtime.Serialization.dll.
You need to reference the System.Runtime.Serialization assembly in your unit test project.
I have a Fixture class that I use for unit testing (test data generator) and I have made these extension methods for it:
public static void SutPropertyHasAttribute<TSut, TProperty>(this Fixture fixture, Expression<Func<TSut, TProperty>> propertyExpression, Type attributeType)
{
var pi = (PropertyInfo)((MemberExpression)propertyExpression.Body).Member;
var count = pi.GetCustomAttributes(attributeType, true).Count();
Assert.AreEqual(1, count);
}
public static void SutHasAttribute<TSut>(this Fixture fixture, Type attributeType)
{
var type = typeof(TSut);
var count = type.GetCustomAttributes(attributeType, true).Count();
Assert.AreEqual(1, count);
}
public static void SutMethodHasAttribute<TSut>(this Fixture fixture, Expression<Action<TSut>> methodExpression, Type attributeType)
{
var mi = (MethodInfo)((MethodCallExpression)methodExpression.Body).Method;
var count = mi.GetCustomAttributes(attributeType, true).Count();
Assert.AreEqual(1, count);
}
Now I call it like this from my tests:
[TestMethod]
public void SutHasDataContractAttribute()
{
// Fixture setup
// Exercise system and verify outcome
new Fixture().SutHasAttribute<Flag>(typeof(DataContractAttribute));
// Teardown
}
[TestMethod]
public void FlagGroupIdHasDataMemberAttribute()
{
// Fixture setup
// Exercise system and verify outcome
new Fixture().SutPropertyHasAttribute((Flag f) => f.FlagGroupId, typeof(DataMemberAttribute));
// Teardown
}
The Flag class looks like this:
[DataContract(Namespace ="http://mynamespace")]
public class Flag
{
[DataMember]
public string FlagGroupId { get; set; }
}
Of course you need a reference to System.Runtime.Serialization like this:
using System.Runtime.Serialization;