0

I want to execute one Test method several (3) times with different behaviour of a mocked object. So I can avoid writing multiple Test methods with mocked objects for each.

Code as example:

_mockObj.MockedMethod(Arg.Any<string>(), Arg.Any<string>()).Returns(new objA() { TestProp="bla1" };
_mockObj.MockedMethod(Arg.Any<string>(), Arg.Any<string>()).Returns(new objA() { TestProp="bla2" };
_mockObj.MockedMethod(Arg.Any<string>(), Arg.Any<string>()).Returns(new objA() { TestProp="bla3" };

What I want to do is by using one Test method to test the above 3 behaviours. Is this possible or do I have to write 3 separate Test methods?

EDIT

I've found that I have to use TestCaseSourceAttribute. But now I'm facing another 'issue'. When I have a lot of TestCases and one of them fails, then I can't trace which one of the TestCases failed...

Ozkan
  • 3,880
  • 9
  • 47
  • 78
  • 1
    You can write one method that's either used by 3 test methods or is called 3 times by one test method just like in regular code. – juharr May 30 '17 at 12:00
  • You mean I can write 3 separate Arrange, Act, Asserts in one Test method? – Ozkan May 30 '17 at 12:20
  • That's one way to look at it, but I'd thing writing the common Arrage, Act, and Assert code into the "helper" method and then call it passing in the different mocks would be my suggestion. Wheather you call that from one Test method or 3 is up to you. I'd still do 3 separate tests methods so that I could see the asserts/errors for each one. – juharr May 30 '17 at 12:23

2 Answers2

2

A method != a test. Using parameters, one method makes many test cases. For example...

[TestCase("bla1")]
[TestCase("bla2")]
[TestCase("bla3")]
public void MyTest(string blaValue)
{
    _mockObj.MockedMethod(Arg.Any<string>(), Arg.Any<string>())
        .Returns(new objA() { TestProp=blaValue };

    // Your test code
}
Charlie
  • 12,928
  • 1
  • 27
  • 31
  • Thanks but my attribute argument is actually not a compile-time constant. It's an object. I wanted to make my example as simple as possible – Ozkan May 31 '17 at 06:38
1

Some research led me to this: https://stackoverflow.com/a/10687118/1410501

[Test, TestCaseSource(nameof(MyTestCases))]
public void TestMethod(object obj)
{

}

private static readonly object[] MyTestCases =
{
    new object { TestProp="bla1" },
    new object { TestProp="bla2" },
    new object { TestProp="bla3" },
};
Ozkan
  • 3,880
  • 9
  • 47
  • 78