I have to do a simple unit test to check if UpdateScript is being called when DateTimeChanged is called. I would like to use mock for UpdateScript because it is a complex legacy code.
I tried using the Mocks and Stubs, but that is not working. Is there a way to mock just the sub method?
public void DateTimeChanged()
{
if (isToggleOn)
{
this.UpdateScript();
}
}
Related
When writing Unittests, I wonder if it is best practice to create a property for the mock like in this example (I am seeing this all over the tutorials in the internet):
public class CartControllerTests
{
private CartController controller;
private Mock<IPaymentService> paymentServiceMock;
[SetUp]
public void Setup()
{
cartServiceMock = new Mock<ICartService>();
}
}
(Taken and adjusted from https://softchris.github.io/pages/dotnet-moq.html#full-code)
Because when I write several Unittests and Setup the mock for a specific behaviour (per test), I think it could be possible, that one setup in the first test could override the second setup in the next test.
Wouldn't it be better to create an own Mock for every Unittest, and just setup it for the specific Test?
My team is just getting started with using MassTransit and we are trying to figure out how unit testing IConsumer implementations work. The MassTransit documentation is incomplete and all of the examples I have found so far use NUnit. We are trying to use XUnit with Moq to do our unit testing.
I know that we need to set up one instance of the MassTransit test harness, which in NUnit is done with a OneTimeSetup and to replicate that we should use IClassFixture in XUnit. I'm struggling with getting that to work with the test harness, though.
I have seen Chris Patterson's ConsumerTest_Specs.cs example on the MassTransit GitHub, but I'm having a hard time translating it to work in XUnit and Moq.
https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs
I'm trying to test a very simple consumer to start with. All it does is receive the message and then make a call to a repository. I want to write an XUnit test that mocks the repository and verifies that the repository method was called.
Does anyone have any examples of how to do something like this?
public class NewVMRequestRejectedConsumer : IConsumer<INewVMRequestRejected>
{
private readonly INewVMRequestRepository _newVMRequestRepository;
public NewVMRequestRejectedConsumer(INewVMRequestRepository newVMRequestRepository)
{
_newVMRequestRepository = newVMRequestRepository;
}
public Task Consume(ConsumeContext<INewVMRequestRejected> context)
{
_newVMRequestRepository.AddReasonForRejection(context.Message.RequestId, context.Message.Reason);
return Task.CompletedTask;
}
}
Since ConsumeContext<out T> and INewVMRequestRepository are interfaces there is no problem mocking them using moq, e.g.
//Arrange
var repository = new Mock<INewVMRequestRepository>();
var sut = new NewVMRequestRejectedConsumer(repository.Object);
//Act
sut.Consume(Mock.Of<ConsumeContext<INewVMRequestRejected>>(m =>
m.Message.RequestId == "id" && m.Message.Reason == "reason"));
//Assert
repository.Verify(m => m.AddReasonForRejection("id", "reason"), Times.Once);
I'm a bit confused with writing unit tests in C#. I've written the following class for learning Moq. I've noticed the [SetUp] is actually a reference from NUnit. How can I write a test class that only uses one framework or another or whether that's possible? If I want to use Moq what attributes am I missing to successfully run this test? I know there's [TestFixture], [TestMethod] etc.. but which one do I use for Moq!
Thanks,
James
public class CatalogCommandTests
{
private Mock<IReferenceData> _mockReferenceData;
[SetUp]
public void TestInitialize()
{
_mockReferenceData = new Mock<IReferenceData>();
}
public void TestMyGetMethodReturnsListOfStrings()
{
var contractsList = new List<Contract>();
_mockReferenceData.Setup(x => x.MyGetMethod()).Returns(contractsList);
}
}
Your mock looks good. To get the mock of IReferenceData you have to call _mockReferenceData.Object.
A method decorated with the SetUp Attribute will be executed before each test method is called.
(See: Setup).
If you want that TestMyGetMethodReturnsListOfStrings gets called you have to decorate the method with the Test attribute
(See: Test).
I am having trouble getting my Method B test to run. The logic is fine, but when the unit tests are run, only Method A will run. If Method A and B are switched in terms of spots, only Method B will run. So clearly the code is wrong at some point. Do I need to call method B's test from inside method A in order to get both unit tests to run?
I'm pretty new to C#, so forgive my basic question.
using redacted;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace UnitTests
{
[TestClass()]
public class ClassTest
{
public TestContext TestContext{get;set;}
[TestMethod()]
public void MethodATest()
{
the unit test
}
[TestMethod()]
public void MethodBTest()
{
the unit test
}
}
}
Looks fine.
Make sure you are running all test (Test->Run->All tests), not something like test in context (Ctrl+R, T) or have some sort of list of tests to run.
I'm trying to implement a unit test for a function in a project that doesn't have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I've been trying to create this object by using code such as...
System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);
...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test.
How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?
When I've been faced with this sort of problem (where the class in question doesn't implement an interface), I often end up writing a wrapper with associated interface around the class in question. Then I use my wrapper in my code. For unit tests, I hand mock the wrapper and insert my own mock object into it.
Of course, if a mocking framework works, then use it instead. My experience is that all mocking frameworks have some issues with various .NET classes.
public interface ICacheWrapper
{
...methods to support
}
public class CacheWrapper : ICacheWrapper
{
private System.Web.Caching.Cache cache;
public CacheWrapper( System.Web.Caching.Cache cache )
{
this.cache = cache;
}
... implement methods using cache ...
}
public class MockCacheWrapper : ICacheWrapper
{
private MockCache cache;
public MockCacheWrapper( MockCache cache )
{
this.cache = cache;
}
... implement methods using mock cache...
}
public class MockCache
{
... implement ways to set mock values and retrieve them...
}
[Test]
public void CachingTest()
{
... set up omitted...
ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() );
CacheManager manager = new CacheManager( wrapper );
manager.Insert(item,value);
Assert.AreEqual( value, manager[item] );
}
Real code
...
CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));
manager.Add(item,value);
...
I think your best bet would be to use a mock object (look into Rhino Mocks).
A very useful tool for unit testing legacy code is TypeMock Isolator. It'll allow you to bypass the cache object entirely by telling it to mock that class and any method calls you find problematic. Unlike other mock frameworks, TypeMock uses reflection to intercept those method calls you tell it to mock for you so you don't have to deal with cumbersome wrappers.
TypeMock is a commercial product, but it has free versions for open-source projects. They used to have a "community" edition that was a single-user license but I don't know if that's still offered.
var httpResponse = MockRepository.GenerateMock<HttpResponseBase>();
var cache = MockRepository.GenerateMock<HttpCachePolicyBase>();
cache.Stub(x => x.SetOmitVaryStar(true));
httpResponse.Stub(x => x.Cache).Return(cache);
httpContext.Stub(x => x.Response).Return(httpResponse);
httpContext.Response.Stub(x => x.Cache).Return(cache);