diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs index 5f8df2bf94..3b25f20c11 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs @@ -192,6 +192,7 @@ private TestResult ExecuteInternal(object[] arguments) var classInstance = this.CreateTestClassInstance(result); var testContextSetup = false; bool isExceptionThrown = false; + bool hasTestInitializePassed = false; Exception testRunnerException = null; try @@ -205,6 +206,7 @@ private TestResult ExecuteInternal(object[] arguments) if (this.RunTestInitializeMethod(classInstance, result)) { + hasTestInitializePassed = true; PlatformServiceProvider.Instance.ThreadOperations.ExecuteWithAbortSafety( () => this.TestMethod.InvokeAsSynchronousTask(classInstance, arguments)); result.Outcome = TestTools.UnitTesting.UnitTestOutcome.Passed; @@ -246,7 +248,8 @@ private TestResult ExecuteInternal(object[] arguments) // if we get here, the test method did not throw the exception // if the user specified that the test was going to throw an exception, and // it did not, we should fail the test - if (!isExceptionThrown && this.ExpectedException != null) + // We only perform this check if the test initialize passes and the test method is actually run. + if (hasTestInitializePassed && !isExceptionThrown && this.ExpectedException != null) { result.TestFailureException = new TestFailedException( UnitTestOutcome.Failed, diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TestMethodInfoTests.cs index 296c4bdb99..3081eaea5d 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TestMethodInfoTests.cs @@ -430,6 +430,23 @@ public void TestMethodInfoInvokeShouldSetStackTraceInformationIfTestInitializeTh " at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.UnitTests.Execution.TestMethodInfoTests.<>c.b__"); } + [TestMethodV1] + public void TestMethodInfoInvokeShouldSetTestInitializeExceptionEvenIfMethodHasExpectedExceptionAttriute() + { + // Arrange. + DummyTestClass.TestInitializeMethodBody = classInstance => { UTF.Assert.Fail("dummyFailMessage"); }; + this.testClassInfo.TestInitializeMethod = typeof(DummyTestClass).GetMethod("DummyTestInitializeMethod"); + const string ErrorMessage = "Assert.Fail failed. dummyFailMessage"; + var testMethodInfo = new TestMethodInfo(this.methodInfo, 3600 * 1000, this.testMethodAttribute, this.expectedException, this.testClassInfo, this.testContextImplementation); + + // Act. + var exception = testMethodInfo.Invoke(null).TestFailureException as TestFailedException; + + // Assert. + Assert.IsNotNull(exception); + Assert.AreEqual(ErrorMessage, exception?.Message); + } + #endregion #region TestCleanup method setup