Telerik Forums
JustMock Forum
1 answer
19 views

In Visual Studio 2022, the first quick action is often "Create Mock". As this is used in the overlay when hovering over a method, I see "JMA001" quite often, which is not helpful when writing non-test code.

I know that I could create a .editorconfig file to suppress individual hints for every project I work on, but how can I prevent the JustMock hints from being used in the quick actions completely across projects?

Ivo
Telerik team
 answered on 12 Aug 2022
1 answer
24 views

I'm working on tests for legacy code that instantiates a ServiceController (in System.ServiceProcess) to check for a running SQL Server instance. I want to add the tests to our CI/CD build pipeline, so I decided to use JustMock to future-mock ServiceController since the service in question will not exist on the build server. These tests are all using xUnit.

However, the test (which has 3 variants specified via xUnit's InlineData attributes) started hanging on the first variant. It's not just long-running; I've let it run for hours (it's normally a 3-second test at most), and CPU usage is negligible. ServiceController is IDisposable, so I figured it might have something to do with that.

After a lot of paring down, I can repro the problem with the following code in a new project:

public class JustMockTest
{
    [Theory]
    [InlineData("test")]
    public void TestMethod(string whatever)
    {
        Mock.Arrange(() => new ServiceController()).DoNothing();
    }
}

However, this test (in the same class) works fine and completes in about 1s - note that it's a fact, not a theory:

[Fact]
public void TestMethod2()
{
    Mock.Arrange(() => new ServiceController()).DoNothing();
}

This is JustMock v2022.1.223.1, xUnit v2.4.1.0, and VS 2022.

At first I wondered if my 3 variants were somehow stepping on each other's Mock.Arrange() statements; but as you can see, the top test, while declared as a theory, only has 1 variant and still has the problem. What's also interesting is that an analogous setup for MSTest also runs fine - so this seems to be xUnit-specific somehow:

[TestClass]
public class UnitTest1
{
    [DataTestMethod]
    [DataRow("test")]
    [DataRow("test2")]
    public void TestMethod1(string whatever)
    {
        Mock.Arrange(() => new ServiceController()).DoNothing();
    }
}

At first I thought IDisposable classes may be the problem, but it seems it's actually MarshalByRefObject; it's a base class of ServiceController and others I can repro with (WebClient, MemoryStream, etc.), and I can also repro by mocking a simple class of my own that extends MarshalByRefObject.

Is this a known issue? Are there recommended workarounds (without having to ditch xUnit for MSTest or another framework)?

Thanks!
Jeremy

Ivo
Telerik team
 answered on 06 Jul 2022
2 answers
145 views

Hi,

I am trying to run to  Dotnet Test command for .NetCore dll in Azure Devops and It throws exception for some tests saying elevated Mocking Exception.

 

Comand Used is

taskDotNetCoreCLI@2
  displayNamedotnet test - Unit Tests
  inputs:
    commandtest
    projects'**/*.UnitTest.csproj'
    arguments--no-build --configuration $(BuildConfiguration) --logger trx --collect "Code coverage" /p:CollectCoverage=true /p:Threshold=0 /p:ThresholdType=line /p:CoverletOutputFormat=cobertura /p:CoverletOutput=$(Build.SourcesDirectory)/TestResults/Coverage /p:ExcludeByAttribute="DebuggerNonUserCodeAttribute" /p:ExcludeByFile=\"**/obj/**/*.cs"
    testRunTitleUnit Tests
Yanrafo
Top achievements
Rank 1
Iron
 answered on 06 Jul 2022
1 answer
50 views

I want the Mock to return the SQL statement and Not execute the statement. This is what i have done but it keeps running the "connection.execution(SQL)".  

                         

 

string SQL = "";

            Mock.Arrange(() => connection.Execute(Arg.AnyString, null, null, null, null)).DoInstead((string arg1) => { SQL = arg1; }).IgnoreInstance().Returns(1);



            WebApiProject.Controllers.DeleteController dc = new WebApiProject.Controllers.DeleteController();
           
            dc.Post(mockedDeleteObject);

            Assert.IsTrue(SQL == $"DELETE FROM TEST WHERE 1=1");

 

 

Post{

                string SQL;
                SQL = $"delete from {TableName}  where  {WhereClause} ";

                con.Execute(SQL,parameters );}

 

 

 

But it keeps running the sql executable statement

 

 

 

faul
Top achievements
Rank 1
Iron
 answered on 04 Jul 2022
1 answer
35 views

Hi,

I'm interested in Telerik JustMock, so I'm installing and testing a trial version of JustMock.
The worry is that my development environment is disconnected from the Internet, so when I purchase the full version, it cannot be installed.
Are there any problems with the installation and operation of the full version even in an environment where the Internet is disconnected?

Thank you.
Xavime
Top achievements
Rank 1
Iron
 updated answer on 04 Jul 2022
5 answers
1.1K+ views
01.
[Fact]
02.public void Reconcile_LocationGroupChangedEvent_ReconcileSuccessfully()
03.{
04.    using (var container = new MockingContainer<Assignment>(settings))
05.    {
06.        //Arrange
07.        container.Arrange<IFacade>(x =>x.Initialize()).OccursAtMost(1);
08.                 
09.        //Act
10.        container.Instance.Reconcile();
11. 
12.        //Assert
13.        container.AssertAll();
14.    }
15.}
16. 
17.// Method under test
18. 
19.public void Reconcile()
20.
21.    Task.Factory.StartNew(() => facade.Initialize());
22.}

 

I am getting intermittent errors when running the above Test. It fails so infrequently that I am unable to debug. When it fails, here is what I see in the logs.

Reconcile_Test [FAIL]
System.InvalidOperationException : Collection was modified; enumeration operation may not execute.
Stack Trace:
     at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
     at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
     at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
     at System.Linq.Enumerable.<SelectManyIterator>d__23`3.MoveNext()
     at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
     at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
     at Telerik.JustMock.Core.MocksRepository.GetDebugView(Object mock)
     at Telerik.JustMock.DebugView.<>c.<get_CurrentState>b__1_0()
     at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
     at Telerik.JustMock.DebugView.TraceEvent(IndentLevel traceLevel, Func`1 message)
     at Telerik.JustMock.Core.Context.MockingContext.ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior)
     at Telerik.JustMock.Helpers.FluentHelper.<>c__DisplayClass13_0`1.<AssertAll>b__0()
     at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
     at Telerik.JustMock.AutoMock.MockResolver.ForEachMock(Action`1 action)
     at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
  E:\agt01\COM-CN-JOB1\AssignmentTest.cs(14,0): at AssignmentTest.Reconcile_Test()
Ivo
Telerik team
 answered on 15 Feb 2022
2 answers
180 views

Unfortunately my JustMock does not work anymore. I get this exception:

  Message: 
    Test method ActuIT.Futurama.Test.TestEdit.EditorTest threw exception: 
    Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'System.IO.File'. The profiler must be enabled to mock, arrange or execute the specified target.

  Stack Trace: 
    ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
    MocksRepository.InterceptStatics(Type type, MockCreationSettings settings, Boolean mockStaticConstructor)
    <>c__DisplayClass69_0.<SetupStatic>b__0()
    ProfilerInterceptor.GuardInternal(Action guardedAction)
    Mock.SetupStatic(Type staticType, Behavior behavior)
    TestEdit.PerformTest(TestInput testInput, String& logFile) line 1413
    TestEdit.PerformTest(String testFile, String& logFile) line 1400
    TestEdit.EditorTest() line 360

Some background:

- I started of with VS2019 version 16.10.4 and JustMock version 2019.2.620.1

- Profiler is enabled in Extensions->JustMock

- tried to reinstall -> no effect

- upgraded VS2019 to 16.11.9 -> no effect

- upgraded to JustMock 2022.1.119.1 -> no effect

- Above is just a sample, all of my unit tests that use JustMock fail

- I checked a colleague and he had exactly the same problem

Any setting/config I might have missed?

Regards,

Dirk

 

 

 

 

 

 

Chris Vrolijk
Top achievements
Rank 1
Iron
 answered on 31 Jan 2022
2 answers
175 views

Hi,

I'm getting the following error for a blazor project using MSTest2 using JustMock flite.

Message: 
    Test method vx.test.TestsWeb.TestSystemSetup.All_12_Cards_are_found threw exception: 
    System.TypeInitializationException: The type initializer for 'Telerik.JustMock.Core.Context.MockingContext' threw an exception. ---> System.InvalidOperationException: Some attribute type among Xunit.FactAttribute, xunit.core,Xunit.TheoryAttribute, xunit.core not found.
  Stack Trace: 
    HierarchicalTestFrameworkContextResolver.CreateAttributeMatcher(String[] attributeTypeNames)
    HierarchicalTestFrameworkContextResolver.AddRepositoryOperations(String[] attributeTypeNames, Func`2 getKey, Func`3 isInheritingContext, Boolean isLeaf, Boolean isUsedOnAllThreads)
    HierarchicalTestFrameworkContextResolver.SetupStandardHierarchicalTestStructure(String[] testMethodAttrs, String[] testSetupAttrs, String[] fixtureSetupAttrs, String[] assemblySetupAttrs, FixtureConstuctorSemantics fixtureConstructorSemantics)
    XUnit2xMockingContextResolver.ctor()
    MockingContext.cctor()
    --- End of inner exception stack trace ---
    MockingContext.get_CurrentRepository()
    <>c__38`1.<Create>b__38_0()
    ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
    Mock.Create[T]()
    TestSystemSetup.All_12_Cards_are_found() line 25

 

From the following code:

    [TestClass]
    public class TestSystemSetup : Bunit.TestContext
    {
        [TestMethod]
        public void All_12_Cards_are_found()
        {
            // Syncfusion setup
            JSInterop.Mode = JSRuntimeMode.Loose;
            Services.AddSyncfusionBlazor();

            // Arrange
            IApplicationConfigurationSingleton ApplicationConfigurationSingletonMockObj = Mock.Create<IApplicationConfigurationSingleton>();
            Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.Branding_Button_Background_Color).Returns("0xffff");
            Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.Branding_Button_Border_Color).Returns("0xffff");
            Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.Branding_Button_Color).Returns("0xffff");
            Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.IsLicenceExpired).Returns(false);
            Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.DaysValidity).Returns(10);
            Services.AddSingleton<IApplicationConfigurationSingleton>(ApplicationConfigurationSingletonMockObj);

            ISystemSetupRepository SystemSetupRepositoryMockObj = Mock.Create<ISystemSetupRepository>();
            Mock.Arrange(() => SystemSetupRepositoryMockObj.GetMenuSummary()).Returns(Task.FromResult(GetSummary_DataSet()));
            Services.AddSingleton<ISystemSetupRepository>(SystemSetupRepositoryMockObj);

            // Act
            IRenderedComponent<SystemSetup> cut = RenderComponent<SystemSetup>();

            // Assert all 12 cards are found
            cut.Find("#Software_licence");
            cut.Find("#Audit_Log");
            cut.Find("#Snapshots");
            cut.Find("#User_Authentication");
            cut.Find("#Source_Of_User_Information");
            cut.Find("#Application_Parameters");
            cut.Find("#Attachments");
            cut.Find("#Data_Export_Profiles");
            cut.Find("#Email_Settings");
            cut.Find("#Custom_Help");
            cut.Find("#Splunk_Settings");
            cut.Find("#ServiceNow_Settings");
        }

}

 

A bit puzzled as to why the error references xunit.

 

michael
Top achievements
Rank 1
Iron
 answered on 21 Oct 2021
1 answer
370 views

Hi, 

Please let me know on how do we mock  a private constructor.

Example:

public class Test
    {
        private Test(int iNum)
        {
            Number = iNum;
        }
        private int Number;
    }
Ivo
Telerik team
 answered on 12 Oct 2021
1 answer
117 views

 public class Sum
    {
        public int GetSum()
        {
            return SumBy2.Add1(10,5);
        }


        public int GetSum2()
        {
            SumBy1 by1 = new SumBy1();
            return by1.Add(10, 5);
        }


        private class SumBy1
        {
            public int Add(int a, int b)
            {
                return a + b;
            }
        }

        private static class SumBy2
        {
            public static int Add1(int a, int b)
            {
                return a + b;
            }
        }
    }

 

Need to create Unit tests for Sum class.

Ivo
Telerik team
 answered on 05 Oct 2021
Narrow your results
Selected tags
Tags
+? more
Top users last month
Chris
Top achievements
Rank 2
Iron
Johnny
Top achievements
Rank 1
Iron
Iron
Iron
Hakob
Top achievements
Rank 2
Iron
Simos Sigma
Top achievements
Rank 2
Iron
Iron
Iron
lahiru
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Top users last month
Chris
Top achievements
Rank 2
Iron
Johnny
Top achievements
Rank 1
Iron
Iron
Iron
Hakob
Top achievements
Rank 2
Iron
Simos Sigma
Top achievements
Rank 2
Iron
Iron
Iron
lahiru
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?