TestContext property is null - visual-studio-2017

i have been tryign to get current test directory from where tests are running.
code that i m using
[TestFixture]
public class ValidatePDF
{
public NUnit.Framework.TestContext TestContext { get; set; }
[SetUp]
public void Init()
{
string t = TestContext.TestDirectory;
}
}
TestContext is always null.
i m using Visual Studio 2017 , and NUnit 3
i have tried with MS TextContext but it always return null
public Microsoft.VisualStudio.TestTools.UnitTesting.TestContext TestContext { get; set; }
[Test]
public void GetMetaInfo()
{
string t = TestContext.TestDir;
}

Remove the MS TestContext, and use NUnit's built in TestContext. Note that it is a static property, so access the CurrentContext's members.

Related

Confusion over unittest assert with class type expectation

Im using .netcore5 and Moq library,im trying to write a test for a method which retunes:
public class CheckResult
{
public bool ShouldBeFlagged { get; set; } = default!;
public decimal ExeededAmount { get; set; } = default!;
}
so,when it comes to assert how should i apply it to the class?my expected result is:
shouldBeFlagged=true;
ExeededAmount=2000M;
any help will be appreciated

Unit testing mvc model with HttpContext.Current.User.Identity.GetUserId()

In my MVC5 application, I have a Log entity, that is used to log any call to any controler. This log uses: HttpContext.Current.User.Identity.GetUserId() to determine the identity of the user accessing the controller.
public class Log
{
public Log()
{
TS = DateTime.Now;
UserId = HttpContext.Current.User.Identity.GetUserId();
}
[Required]
public Int32 Id { get; set; }
public string UserId { get; set; }
[Display(Name = "TS", ResourceType = typeof(Resources.Models.Log.Log))]
[Required(ErrorMessageResourceType = typeof(Resources.Models.Log.Log), ErrorMessageResourceName = "RequiredTS")]
public DateTime TS { get; set; }
[Required]
public short LogTypeId { get; set; }
[Display(Name = "LogText", ResourceType = typeof(Resources.Models.Log.Log))]
public string LogText { get; set; }
public ApplicationUser User { get; set; }
}
When I try to unit test a controller and crating an instance of the log class I get this error:
threw exception: System.NullReferenceException: Object reference not
set to an instance of an object.
at DASU.Core.Models.Log..ctor()
I know this is because the context is not set.
So my question is how do I set the context, or how do I mock the context, so I can create the Log for my test?
You should avoid coupling to HttpContext. Like suggested in the comments you could simplify your log my injecting the UserId into the dependent Log class
public class Log
{
public Log(string userId)
{
TS = DateTime.Now;
UserId = userId;
}
//...other code removed for brevity
}
or abstracting away the calls to HttpContext so that you can mock your abstract and inject that instead of trying and mock HttpContext
public interface IUserProvider {
string GetUserId();
}
You production implementations can wrap calls to HttpContext and you can easily create mock implementations for your unit tests.
public class Log
{
public Log(IUserProvider userProvider)
{
TS = DateTime.Now;
UserId = userProvider.GetUserId();
}
//...other code removed for brevity
}

Cannot mock .... The profiler must be enabled to mock, arrange or execute the specified target

I have the following in a test (my first ever JustMock test, I might add)...
var template = Mock.Create<MessageType>();
Mock.Arrange(() => template.Subject)
.Returns("This template has Zero tokens.");
Mock.Arrange(() => template.Body)
.Returns("This template has {{number}} of {{tokens}}.");
The class being Mocked looks like this ...
public class MessageType : BaseBusinessEntity
{
public string Body { get; set; }
public int DigestsToBeIncludedOn { get; set; }
public Guid MessageReference { get; set; }
public int MessageTypeId { get; set; }
public string Name { get; set; }
public int PredefinedRecipients { get; set; }
public string Subject { get; set; }
}
When I attempt to run the test I get ...
Error Message: Test method
Genesis.Service.Implementation.Tests.DigestFixture.ShouldCorrectlyExtractTemplateTokens
threw exception: Telerik.JustMock.Core.ElevatedMockingException:
Cannot mock 'System.String get_Subject()'. The profiler must be
enabled to mock, arrange or execute the specified target. Stacktrace:
at
Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo
member) at
Telerik.JustMock.Core.MocksRepository.CheckMethodInterceptorAvailable(IMatcher
instanceMatcher, MethodBase method) at
Telerik.JustMock.Core.MocksRepository.AddArrange(IMethodMock
methodMock) at
Telerik.JustMock.Core.MocksRepository.Arrange[TMethodMock](Expression
expr, Func1 methodMockFactory) at
Telerik.JustMock.Mock.<>c__DisplayClass81.b__6() at
Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func1
guardedAction) at Telerik.JustMock.Mock.Arrange[TResult](Expression1
expression) at
Genesis.Service.Implementation.Tests.DigestFixture.ShouldCorrectlyExtractTemplateTokens()
in
c:\Genesis\Development\Genesis.Service.Implementation.Tests\DigestFixture.cs:line
46
Can anyone point out what I've done wrong?
Be sure you have enabled the profiler from the menu.
While using Visual Studio for writing your tests you will notice the Telerik menu and the JustMock menu-item in it. Once there, you have to check if JustMock is enabled(“Enable JustMock” should be grey, see the example bellow).

Invalid column name error with EF 4.1 Code First

I've been having a problem with this for about a day now, I've searched and found similar problems with their solutions but haven't been able to fix this.
I've seen this done with the Teams example, so I'll do the same. I have a Team:
public abstract class Team
{
[Key]
public int IdTeam { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
I also have a Match object:
public class Match
{
[Key]
public int IdMatch { get; set; }
[ForeignKey("HomeTeam")]
public int IdHomeTeam { get; set; }
[ForeignKey("AwayTeam")]
public int IdAwayTeam { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team AwayTeam { get; set; }
}
Whenever I try to access the name of either team I get an Invalid column name Team_TeamId error. I'm guessing it has something to do with EF and the Foreign Keys not being mapped correctly. I've also seen other people use ICollections, but I don't think I need them for this case.
You have to fix this in the OnModelCreating method. Entity framework can't seem to recognize the foreign keys, so you have to specify it specifically.
public class Entities : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Match>()
.HasRequired(b => b.AwayTeam)
.WithMany()
.HasForeignKey(b => b.IdAwayTeam);
modelBuilder.Entity<Match>()
.HasRequired(b => b.HomeTeam)
.WithMany()
.HasForeignKey(b => b.IdHomeTeam);
}
}
for more information about code first OnModelCreating check this: http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.onmodelcreating(v=vs.103).aspx

How to get test result status from MSTest?

In NUnit, I can get the test result from context.Result.State. If its NUnit.Framework.TestState.Success, then I know the test passed.
In MSTest, how do I get that info?
I saw context.Properties.Keys, but none of them speak of the status of the test result.
Use the TestContext.CurrentTestOutcome property in the TestCleanup method:
[TestClass]
public class UnitTest
{
private TestContext TestContext { get; set; }
[TestCleanup]
public void TestCleanup()
{
if (TestContext.CurrentTestOutcome == UnitTestOutcome.Passed)
//do something
}
[TestMethod]
public void TestMethod()
{
}
}