I'm actually facing an issue using TestContext in MSTest. When I add a property to the context, it doesn't exist when I try to get it in another test method. Can someone explain me why or know how to fix it? Here is my code sample:
I can't get why i can Console.Writeline the value I need in Action1() but can't access it in Action2()
Thanks :)
namespace API.Tests.Controllers
{
[TestClass]
public class ControllerTests
{
private SomeController _controller;
private SomeService _somService;
public TestContext TestContext { get; set; }
[TestInitialize]
public void Initialize()
{
_someService = new SomeService();
}
[TestMethod]
public void Action2()
{
// Arrange
var criteria = TestContext.Properties["id"]; <-- Can't access value here, it doesn't exist
SomeController _controller = new SomeController(_someService);
// Act
IHttpActionResult result = _controller.Search((string)criteria);
// Assert
var contentResult = result as OkNegotiatedContentResult<List<Object>>;
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result,typeof(OkNegotiatedContentResult<List<Object>>));
}
[TestMethod]
public void Action1()
{
// Arrange
var testObj = new Obj
{
id = 10,
name = "Test",
code = "XXX"
};
SomeController _controller = new SomeController(_someService);
// Act
IHttpActionResult result = _controller.Create(testObj);
// Assert
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult<int>));
var content = result as OkNegotiatedContentResult<int>;
TestContext.Properties.Clear();
TestContext.Properties.Add("id", content.Content.ToString());
Console.WriteLine(TestContext.Properties["id"]); <-- I can get the value here
Console.WriteLine(TestContext.Properties.Count); <-- equal to 1
}
}
}