I have an NUnit test
[TestCase(...)]
public void test_name(Action onConfirm)
{
...
}
What I want to do is pass an Action into this test in the TestCase attribute, but no matter what I try keeps failing. I tried to put
() => SomeDummyMethodIDefined()
directly into the TestCase and that didn't work.
I created an Action
Action DummyAction = () => SomeDummyMethodIDefined();
and pass DummyAction into the TestCase and that didn't work.
Is there a way to do this?
This is a very rough example which I was inspired from reading the NUnit docs here
namespace NUnitLambda
{
using System;
using NUnit.Framework;
[TestFixture]
public class Class1
{
[Test]
[TestCaseSource(typeof(SourceClass), "TestCases")]
public void Foo(Action action)
{
action();
}
}
public class SourceClass
{
private static Action t = () => Console.WriteLine("Hello World");
public static Action[] TestCases = { t };
}
}
Have a play around with the code, hopefully you will get what you want out of it. For the record, I was using NUnit 2.6.
EDIT:
You don't have to use static here either e.g.
public class SourceClass
{
private Action t = () => Console.WriteLine("Hello World");
public Action[] TestCases;
public SourceClass()
{
TestCases = new Action[1];
TestCases[0] = t;
}
}
Related
I would like to be able to simulate a failure of an arbitrary test in order to check that my TearDown logic works correctly. A unit test on a unit test, if you please.
But really, I have TearDown in some fixtures that produces attachments on failures. I must be able to show off this feature, but it is hard to produce a failure when you most need it.
So, I want to create a test parameter specifying the name of a test I wish to fail. Now, I can easily write an attribute implementing IWrapTestMethod or IApplyToContext, but then I need to apply it on every test method.
Is there a way to implement it without touching every test and/or fixture? By some kind of an assembly level attribute or assembly level setup method that would run before each and every test?
It is crucial that this logic would not prevent the TearDown methods from running, so ITestAction throwing an exception from BeforeTest does not fit the bill.
Can this be done?
I found the solution:
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using System;
using System.Reflection;
[assembly: Common.EnableFailureSimulation]
namespace Common
{
public class SimulateFailureMethodInfoWrapper : IMethodInfo
{
private readonly IMethodInfo m_mi;
public SimulateFailureMethodInfoWrapper(IMethodInfo mi)
{
m_mi = mi;
}
public ITypeInfo TypeInfo => m_mi.TypeInfo;
public MethodInfo MethodInfo => m_mi.MethodInfo;
public string Name => m_mi.Name;
public bool IsAbstract => m_mi.IsAbstract;
public bool IsPublic => m_mi.IsPublic;
public bool ContainsGenericParameters => m_mi.ContainsGenericParameters;
public bool IsGenericMethod => m_mi.IsGenericMethod;
public bool IsGenericMethodDefinition => m_mi.IsGenericMethodDefinition;
public ITypeInfo ReturnType => m_mi.ReturnType;
public T[] GetCustomAttributes<T>(bool inherit) where T : class => m_mi.GetCustomAttributes<T>(inherit);
public Type[] GetGenericArguments() => m_mi.GetGenericArguments();
public IParameterInfo[] GetParameters() => m_mi.GetParameters();
public object Invoke(object fixture, params object[] args)
{
var res = m_mi.Invoke(fixture, args);
Assert.Fail("Failure simulation");
return res;
}
public bool IsDefined<T>(bool inherit) where T : class => m_mi.IsDefined<T>(inherit);
public IMethodInfo MakeGenericMethod(params Type[] typeArguments) => m_mi.MakeGenericMethod(typeArguments);
}
[AttributeUsage(AttributeTargets.Assembly)]
public class EnableFailureSimulationAttribute : Attribute, ITestAction
{
private static string s_failTestMethod = GetParameterByName("!");
public ActionTargets Targets => ActionTargets.Test;
public void AfterTest(ITest test)
{
}
public void BeforeTest(ITest test)
{
if (test.MethodName == s_failTestMethod && test is Test testImpl)
{
testImpl.Method = new SimulateFailureMethodInfoWrapper(testImpl.Method);
s_failTestMethod = "!";
}
}
}
}
An alternative approach would be to use Moq and mock the IMethodInfo interface instead of having the real SimulateFailureMethodInfoWrapper class.
Anyway, this seems to work perfectly.
I am new to RhinoMocks, and I am trying to write a test as shown
I have classes like these
public class A
{
public void methodA(){}
}
public class B
{
public void methodB(A a)
{
a.methodA();
}
}
And i am trying to test it like this
A a = MockRepository.GenerateMock<A>();
public void ShouldTest()
{
B b = new B();
b.methodB(a);
a.AssertWasCalled(x=>x.methodA());
a.VerifyAllExpectations();
}
But it is giving the error as shown:
System.InvalidOperationException : No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call.
How do I test methodB then?? Can someone help??
Rhino mock creates proxy class when you call MockRepository.Generate *** method. This means that it extends your type. If you don't declare any abstraction you cannot make any derivation which is essential in any mocking framework.
You can do two things
Create an interface (better design)
Make the member virtual (this will allow RhinoMocks to derive from your type and create a proxy for the virtual member
Sample code
public interface IA { void methodA();}
public class A:IA{public void methodA() { }}
public class B
{
public void methodB(IA a)
{
a.methodA();
}
}
[TestFixture]
public class Bar
{
[Test]
public void BarTest()
{
//Arrange
var repo = MockRepository.GenerateMock<IA>();
//Act
B b = new B();
b.methodB(repo);
//Assert
repo.AssertWasCalled(a => a.methodA());
repo.VerifyAllExpectations();
}
}
You have concrete classes with no virtual methods and no interfaces. You can't mock anything.
Update:
Here's one way to do it:
public interface IA
{
void methodA();
}
public class A : IA
{
public void methodA(){}
}
public class B
{
public void methodB(IA a)
{
a.methodA();
}
}
Then use
IA a = MockRepository.GenerateMock<IA>();
namespace MoqSample.Test
{
[TestFixture]
public class GivenCustomerServiceTest
{
private ICustomerService customerService;
private CustomerModel customer;
// Defining the mock object.
private Mock<ICustomerRepository> mockCustomerRepository;
[SetUp]
public void SetUp()
{
//Creating the mock object.
mockCustomerRepository = new Mock<ICustomerRepository>();
customerService = new CustomerService(mockCustomerRepository.Object);
}
[Test]
public void GetCustomerByIdTest()
{
customer = new CustomerModel { Id = 1, Name = "TEST-CUSTOMER", Address = "abc" };
mockCustomerRepository.Setup(customerRepository => customerRepository.GetCustomerById(1)).Returns(customer);
var customerReturned = customerService.GetCustomerById(1);
//Verifying values.
Assert.AreEqual(customer.Id, customerReturned.Id);
Assert.AreEqual(customer.Name, customerReturned.Name);
Assert.AreEqual(customer.Address, customerReturned.Address);
}
}
}
When I am trying to debug the code in aforementioned class , it's not hitting the break point.
I.e I am unable to debug the code.
Any suggestions are welcome.
Using the Resharper or TestDriven test runners should allow you to debug through your unit tests.
Running on Eclipse Galileo (3.5), I noticed my tests show the timing of each test run. Is there a way to capture and this information? Is there an API or is it stored in a result file?
Screenshot
http://ge.tt/3ylDyiq
We could use Rule to get time durations for each test method:
class TimeConsumeRule implements MethodRule {
#Override
public Statement apply(final Statement base, final FrameworkMethod method, Object target) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
long start = System.currentTimeMillis();
try {
base.evaluate();
} finally {
System.out.println(method.getName()+ " used "+ (System.currentTimeMillis() - start)+" ms;");
}
}
};
}
}
public class TimeConsume {
//Just declare customized Rule in your test case.
#Rule
public MethodRule rule = new TimeConsumeRule();
#Test
public void test1(){
//...
}
#Test
public void test2(){
//...
}
}
Currently I have a class that looks like this:
public class MyClass : IMyClass
{
public MyClass()
{
//...
}
public MyClass(IMyRepository repository)
{
//...
}
}
In my config file I have IMyClass registered, but not IMyRepository. My intention is for Windsor to use the constructor that doesn't take any parameters, but I am getting this message:
Can't create component 'MyClass' as it
has dependencies to be satisified.
MyClass is waiting for the following
dependencies:
Services:
- Namespace.IMyRepository which was not registered.
I found another post that says that the container will call the constructor with the most arguments that it can satisfy. So why is it trying to call the constructor with an argument that it doesn't know how to satisfy?
Maybe you're using an old version of Windsor... this works just fine for me:
[TestFixture]
public class WindsorTests {
public interface ISomeInterface {}
public class AService {
public int Id { get; private set; }
public AService() {
Id = 1;
}
public AService(ISomeInterface s) {
Id = 2;
}
}
[Test]
public void Parameters() {
var container = new WindsorContainer();
container.AddComponent<AService>();
var service = container.Resolve<AService>();
Assert.AreEqual(1, service.Id);
}
}