Hi,
I am new to justmock, bear with me if I have some basic questions wrong.
We have few unit tests that run fine when I run them locally, but when I checkin them in TFS then it fails the gated-checkin.
I know this can be caused from a range of reasons, but I have reason to believe that one of the mocked method is not getting mocked in the server.
Here is how the code looks,
public void My_Failing_Test()
{
Test_Class_Accessor target = new Test_Class_Accessor();
target.DataLayer = GetMockLayer();
// Set up data
Test_Class mockTest = new Test_Class();
Mock.NonPublic.Arrange<
bool
>(mockPharm, "MockedPrivateMethod", ArgExpr.IsAny<
String
>(), ArgExpr.IsAny<
String
>(), ArgExpr.IsAny<
DateTime
>()).IgnoreArguments().IgnoreInstance().Returns(false);
target.UnderTestPrivateMethod();
//Asserts
}
UnderTestPrivateMethod has a call to MockedPrivateMethod
private static DataLayer GetMockLayer(......)
{
Features mockFeatures = Mock.Create<
Features
>(Constructor.NotMocked, Behavior.CallOriginal);
mockFeatures.someThing = new SomeThing{.....};
DataLayer mockLayer = Mock.Create<
DataLayer
>(Constructor.NotMocked, Behavior.CallOriginal);
mockLayer.TwoTier_Initialize();
Mock.Arrange(() => mockLayer.Features).Returns(mockFeatures);
return mockLayer;
}
I suspect for some reason both the mockFeatures.someThing and MockedPrivateMethod are not getting mocked.
Is there something wrong with what I am doing?
If someone has faces similar problem before, please let me know.
Appreciate the time, thanks
I'm wondering whether I am simply trying to achieve the impossible, but.....
I have successfully mocked up some legacy code and able to run my tests. I have then built a simple WPF app to utilise the same mocking approach and publish the results (without using test fixtures)
However, when I try to run the app outside of visual studio, I get the following exception:
Telerik.JustMock.Core.ElevatedMockingException
Message=Cannot mock 'System.String get_blah()'. The profiler must be enabled to mock, arrange or execute the specified target.
Source=Telerik.JustMock
I have checked the event viewer and the profiler is enabled.
Is this issue simply that this will never run outside of Visual Studio/any other test runner?
Ideally, we would like to be able to create a suite of automated regression testing apps for non-devs to use.
Kind Regards
ben
Hi all,
I have the following generic method in my class:
1.
private T ValidateApiResponse<
T
>(Document response) where T : ResponseBase
2.
{
3.
}
My test method looks like this:
01.
[TestMethod]
02.
public void CardCaptureRequest_CallsCreateRequest()
03.
{
04.
//Arrange
05.
var methodCalled = false;
06.
var facadeSettings = MockFacadeSettings("http://localhost", "logfile", 1, 2, "proxy");
07.
var authSettings = MockAuthenticationSettings("clientName", "password");
08.
var facade = Mock.Create<
DatacashFacade
>(Behavior.CallOriginal, new object[] { facadeSettings, authSettings });
09.
var document = Mock.Create<
Document
>();
10.
var ccResponse = new CardCaptureResponse
11.
{
12.
Status = 1,
13.
DatacashReference = "refNo",
14.
Information = "Info",
15.
MerchantReference = "merchRef",
16.
RedirectUrl = "http://localhost/",
17.
Success = true
18.
};
19.
20.
Mock.NonPublic.Arrange<
Document
>(facade, "CreateRequest")
21.
.DoInstead(() =>
22.
{
23.
methodCalled = true;
24.
}).Returns(document);
25.
Mock.NonPublic.Arrange<
Document
>(facade, "SendRequest")
26.
.IgnoreInstance().Returns(document);
27.
28.
Mock.NonPublic.Arrange<
CardCaptureResponse
>(facade, "ValidateApiResponse", document)
29.
.Returns(ccResponse);
30.
31.
//Act
32.
facade.CardCaptureRequest(1, "", 2, "", "", "");
33.
34.
//Assert
35.
Assert.IsTrue(methodCalled);
36.
}
Line 28 is attempting to Mock the private method call.
However, the test fails with the following: Method 'ValidateApiResponse' with the given signature was not found on type .......
Any ideas??
from audit
in
_context.Audits
where audit.DTS < EntityFunctions.TruncateTime(mydate)
select audit
var fakeEntities = Mock.Create<SomeDBEntities>();
var audits = GetAudits();
Mock.Arrange(() => fakeEntities.Audits).ReturnsCollection(audits);
var target =
new
ReportRepository(fakeEntities);
var result = target.test(DateTime.Now);
Assert.AreEqual(2, result.Count());
Here is an example of what I'd like to mock up?
namespace
ExternalAssembly
{
internal
enum
HintArg { Flag1,Flag2,Flag3}
public
class
ExternalClass
{
private
int
MethodToMock(
string
name, HintArg hint,
out
string
result)
{
result =
"I want to override this"
;
return
0;
}
}
}
In this example what I'd like to have is a setup that will call the original MethodToMock on everything except when I have a specific name match?
I have something along the lines of:
string
mockName=
"mockName"
;
string
mockResult =
"new result"
;
Mock.NonPublic.Arrange(
typeof
(ExternalClass),
"MethodToMock"
,mockName,ArgExpr.IsAny<HintArg>(),ArgExpr.Out<
string
>(newResult).Returns(0);
I'm just not sure how to specify the arg expression when the type is an internal that my invoking assembly is not friends with?
Downloaded the trial of JustMock since so many of the problems I have been facing are supposed to be addressable with it. I'm attempting to Mock an EF 6.1.3 DBContext. I have can build a test that runs directly against the DB and it works fine, but when I run against the Mocked Context I get an exception.
To be clear I am using JustMock version 2015.3.929.5 also per the documentation I downloaded JustMock.EntityFramework from Nuget version 1.0.1. The Nuget installed incorrectly into the project and tried to explicitly target JustMock 2014.1.1424.1, but I corrected the config file back to the currently referenced version as mentioned above.
Here is my code.
public
class
Account
{
public
int
Id {
get
;
set
; }
[Required]
public
string
ExternalId {
get
;
set
; }
public
string
AccountTimeZone {
get
;
set
; }
public
string
FipsCode {
get
;
set
; }
public
bool
DVREnabled {
get
;
set
; }
public
bool
Enabled {
get
;
set
; }
public
double
CreditLimit {
get
;
set
; }
public
int
SdStreams {
get
;
set
; }
public
int
HdStreams {
get
;
set
; }
[Column(TypeName=
"DateTime2"
)]
public
DateTime CreatedTimeUTC {
get
;
set
; }
[Column(TypeName =
"DateTime2"
)]
public
DateTime LastUpdateTimeUTC {
get
;
set
; }
public
string
CreatedBy {
get
;
set
; }
public
string
UpdatedBy {
get
;
set
; }
public
AccountStatus AccountStatus {
get
;
set
; }
public
List<Device> Devices {
get
;
set
; }
public
List<SubscriberGroup> SubscriberGroups {
get
;
set
; }
public
List<AccountValue> AccountValues {
get
;
set
; }
public
SubscriberInfo SubscriberInfo {
get
;
set
; }
public
Device RecordingDevice {
get
;
set
; }
[Required]
public
Tenant Tenant {
get
;
set
; }
public
List<Phone> Phones {
get
;
set
; }
public
List<AccountHistory> AccountHistory {
get
;
set
; }
}
public
class
Tenant
{
public
int
Id {
get
;
set
; }
public
string
TenantName {
get
;
set
; }
public
string
TenantDescription {
get
;
set
; }
public
string
MediaroomVersion {
get
;
set
; }
public
TenantConfiguration TenantConfiguration {
get
;
set
; }
public
List<Account> Accounts {
get
;
set
; }
public
List<Device> Devices {
get
;
set
; }
public
List<ChangeEvent> ChangeEvents {
get
;
set
; }
}
public
class
EmptyAccount
{
public
void
CreateEmptyAccountInConductor(Account newAccount,
int
tenantId,
string
requestedBy, UnitOfWork uow)
{
var tr =
new
TenantRepository(uow);
var tenant = tr.Find(tenantId);
tenant.Accounts.Add(
new
Account(){ExternalId = newAccount.ExternalId, CreatedBy = requestedBy});
tr.InsertOrUpdate(tenant);
uow.Save();
}
}
public
class
TenantRepository : ITenantRepository
{
private
readonly
ConductorContext _context;
public
TenantRepository(UnitOfWork uow)
{
_context = uow.Context;
}
public
Tenant Find(
int
id)
{
return
_context.Tenants.Find(id);
}
public
void
InsertOrUpdate(Tenant entity)
{
if
(entity.Id ==
default
(
int
))
{
_context.Entry(entity).State = EntityState.Added;
}
else
{
_context.Entry(entity).State = EntityState.Modified;
}
}
}
public
class
ConductorContext : DbContext
{
public
ConductorContext()
{
base
.Configuration.ProxyCreationEnabled =
false
;
}
public
DbSet<Account> Accounts {
get
;
set
; }
public
DbSet<AccountHistory> AccountHistories {
get
;
set
; }
public
DbSet<AccountTemplate> AccountTemplates {
get
;
set
; }
public
DbSet<AccountValue> AccountValues {
get
;
set
; }
public
DbSet<ChangeEvent> ChangeEvents {
get
;
set
; }
public
DbSet<Device> Devices {
get
;
set
; }
public
DbSet<DeviceValue> DeviceValues {
get
;
set
; }
public
DbSet<Phone> Phones {
get
;
set
; }
public
DbSet<SubscriberGroup> SubscriberGroups {
get
;
set
; }
public
DbSet<SubscriberInfo> SubscribersInfo {
get
;
set
; }
public
DbSet<Tenant> Tenants {
get
;
set
; }
public
DbSet<TenantConfiguration> TenantConfigurations {
get
;
set
; }
}
public
class
UnitOfWork : IUnitOfWork<ConductorContext>
{
private
readonly
ConductorContext _context;
public
UnitOfWork()
{
_context =
new
ConductorContext();
}
public
UnitOfWork(ConductorContext context)
{
_context = context;
}
public
int
Save()
{
return
_context.SaveChanges();
}
public
void
Dispose()
{
_context.Dispose();
}
public
ConductorContext Context
{
get
{
return
_context; }
}
}
Direct to DB test that works.
[Test]
public
void
CreateEmptyAccountInConductor4()
{
// Arrange
Database.SetInitializer(
new
DropCreateDatabaseAlways<ConductorContext>());
var ctx =
new
ConductorContext();
var fixture =
new
Fixture();
var account = fixture.Build<Account>()
.Without(p => p.Id)
.Without(p => p.Tenant)
.Without(p => p.AccountHistory)
.Without(p => p.AccountValues)
.Without(p => p.Devices)
.Without(p => p.Phones)
.Without(p => p.SubscriberGroups)
.Without(p => p.SubscriberInfo)
.Without(p => p.RecordingDevice)
.Without(p => p.CreatedTimeUTC)
.Without(p => p.LastUpdateTimeUTC)
.Create();
var tenant = fixture.Build<Tenant>()
.With(p => p.Id, 1)
.With(p => p.MediaroomVersion,
"V2"
)
.Without(p => p.Accounts)
.Without(p => p.Devices)
.Without(p => p.ChangeEvents)
.With(p => p.TenantConfiguration,
new
TenantConfiguration())
.Create();
ctx.Tenants.Add(tenant);
ctx.SaveChanges();
// Act
var sut =
new
EmptyAccount();
sut.CreateEmptyAccountInConductor(account, 1, fixture.Create<
string
>(),
new
UnitOfWork(ctx));
ctx.Dispose();
// Assert
ctx =
new
ConductorContext();
// Force entity to load into context.
var tenantAfter = ctx.Tenants.Find(1);
var accountAfter = ctx.Accounts.Find(1);
Assert.AreEqual(account.ExternalId, ctx.Tenants.Find(1).Accounts.Single(p => p.ExternalId == account.ExternalId).ExternalId);
}
Mocked Context that fails with a NullReferanceException in the InsertOrUpdate method of TenantRepository.
[Test]
public
void
CreateEmptyAccountInConductor3()
{
// Arrange
var ctx = Mock.Create<ConductorContext>().PrepareMock();
var fixture =
new
Fixture();
var account = fixture.Build<Account>()
.Without(p => p.Id)
.Without(p => p.Tenant)
.Without(p => p.AccountHistory)
.Without(p => p.AccountValues)
.Without(p => p.Devices)
.Without(p => p.Phones)
.Without(p => p.SubscriberGroups)
.Without(p => p.SubscriberInfo)
.Without(p => p.RecordingDevice)
.Without(p => p.CreatedTimeUTC)
.Without(p => p.LastUpdateTimeUTC)
.Create();
var tenant = fixture.Build<Tenant>()
.With(p => p.Id, 1)
.With(p => p.MediaroomVersion,
"V2"
)
.With(p => p.Accounts,
new
List<Account>())
.Without(p => p.Devices)
.Without(p => p.ChangeEvents)
.With(p => p.TenantConfiguration,
new
TenantConfiguration())
.Create();
var tenantList =
new
List<Tenant>()
{
tenant
};
ctx.Tenants.Bind(tenantList);
// Act
var sut =
new
EmptyAccount();
sut.CreateEmptyAccountInConductor(account, 1, fixture.Create<
string
>(),
new
UnitOfWork(ctx));
// Assert
Mock.Assert(() => ctx.SaveChanges(), Occurs.Once());
}
My assertion test for the Mocked Context is never even reached in the failing test. At this point I assume I'm doing something wrong. Any idea how I can get this to work because I don't want to be creating dropping my database over and over to run my test. This is just one of many I need to write like this.
Hi,
I am using JustMock for some app.config settings:
Mock.Arrange(() => ConfigurationManager.AppSettings["MyAppSettingKey1"]).Returns("MyAppSettingValue1");
Mock.Arrange(() => ConfigurationManager.AppSettings["MyAppSettingKey2"]).Returns("MyAppSettingValue2");
Mock.Arrange(() => ConfigurationManager.AppSettings["MyAppSettingKey3"]).Returns("MyAppSettingValue3");
However, if I do this, other values that are not explicitly mocked are not available:
var myValue = ConfigurationManager.AppSettings["MyAppSettingKeyNotMocked"])
throws a System.NullReferenceException
Is there a better way to mock Configuration.AppSettings?
Hi,
I have a MessageBox.Show method, which has a CallBack action associated with it. I want to Pass a Mocked parameter to that action, which would eventually execute the action statements based on Parameter passed.
Action<
DialogResult
> callback = (result) =>
{
if (result == DialogResult.Yes)
{
//Do something here
}
};
MessageBox.Show("Are you Sure?","Test App",DialogButton.YesNo, DialogImage.Question,callback);
I tried something like below, but it did not work.
Mock.Arrange(() => dialog.Show(Arg.AnyString, Arg.AnyString,DialogButton.YesNo, DialogImage.Question, Arg.IsAny<
Action
<DialogResult>>())).
DoInstead((Action<
DialogResult
> action) =>
{
action.Invoke(DialogResult.Yes);
});
I want to execute the Original callback, with a mocked DialogResult.
How can we do that?
Thanks in Advance,
Sagar
Hello guys!
I get a Telerik.JustMock.Core.ElevatedMockingException when I run: Mock.Arrange(() => _client.GetAsync(Arg.IsAny<string>())).Returns(ShowMeTheMoney());
static async Task<HttpResponseMessage> ShowMeTheMoney()
{
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.SetConfiguration(new HttpConfiguration());
HttpResponseMessage response = httpRequest.CreateResponse(HttpStatusCode.OK, new List<SmsDTO>() { new SmsDTO()});
return response;
}
[TestMethod]
public void GetAll_NullResultTes3t()
{
//Assert.IsTrue(Mock.IsProfilerEnabled);
_client = Mock.Create<HttpClient>();
_controller = new SmsController(new Persistence(_client));
_controller.Request = new HttpRequestMessage();
Mock.Arrange(() => _client.GetAsync(Arg.IsAny<string>())).Returns(ShowMeTheMoney());
IEnumerable<SmsDTO> actualResult = _controller.GetAll();
CollectionAssert.AllItemsAreNotNull(actualResult.ToList());
}
I use VS2015 Enterprise and I have disabled IntelliTrace(Tools>Options>IntelliTrace: Uncheck the Enable IntelliTrace checkbox). Also I enabled the profiler from the JustMock Menu.
I get the following in Event logs:
Info: .NET Runtime version 4.0.30319.0 - The profiler has requested that the CLR instance not load the profiler into this process. Profiler CLSID: '{9999995d-2cbb-4893-be09-fce80abc7564}'. Process ID (decimal): 7808. Message ID: [0x2516].
Info: TraceLog Profiler component initialized successfully, process vstest.executionengine.x86.exe
Info: .NET Runtime version 4.0.30319.0 - The profiler was loaded successfully. Profiler CLSID: '{9999995d-2cbb-4893-be09-fce80abc7564}'. Process ID (decimal): 7724. Message ID: [0x2507].
Error:
The description for Event ID 0 from source Application cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
Error Handler Exception: System.ServiceModel.CommunicationException: There was an error reading from the pipe: The pipe has been ended. (109, 0x6d). ---> System.IO.IOException: The read operation failed, see inner exception. ---> System.ServiceModel.CommunicationException: There was an error reading from the pipe: The pipe has been ended. (109, 0x6d). ---> System.IO.PipeException: There was an error reading from the pipe: The pipe has been ended. (109, 0x6d).
at System.ServiceModel.Channels.PipeConnection.OnAsyncReadComplete(Boolean haveResult, Int32 error, Int32 numBytes)
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ConnectionStream.EndRead(IAsyncResult asyncResult)
at System.Net.FixedSizeReader.ReadCallback(IAsyncResult transportResult)
--- End of inner exception stack trace ---
at System.Net.Security.NegotiateStream.EndRead(IAsyncResult asyncResult)
at System.ServiceModel.Channels.StreamConnection.EndRead()
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.TransportDuplexSessionChannel.EndTryReceive(IAsyncResult result, Message& message)
at System.ServiceModel.Dispatcher.DuplexChannelBinder.EndTryReceive(IAsyncResult result, RequestContext& requestContext)
at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.EndTryReceive(IAsyncResult result, RequestContext& requestContext) \r\n at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.TransportDuplexSessionChannel.EndTryReceive(IAsyncResult result, Message& message)
at System.ServiceModel.Dispatcher.DuplexChannelBinder.EndTryReceive(IAsyncResult result, RequestContext& requestContext)
at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.EndTryReceive(IAsyncResult result, RequestContext& requestContext)
the message resource is present but the message is not found in the string/message table
Info: .NET Runtime version 4.0.30319.0 - The profiler has requested that the CLR instance not load the profiler into this process. Profiler CLSID: '{b7abe522-a68f-44f2-925b-81e7488e9ec0}'. Process ID (decimal): 6696. Message ID: [0x2516].
According to regedit, CLSID: '{9999995d-2cbb-4893-be09-fce80abc7564} corresponds to IntelliTrace and CLSID: '{b7abe522-a68f-44f2-925b-81e7488e9ec0}' to CodeWeaverProfiler class.
Could you please help?
Thanks!