How can i mock method that has HtttpRequestBase parameter - c#

I have method:
public override someClass getX(HttpRequestBase request){ ... }
now, I want to mock it.
I tried
mockProvider.Setup(x => x.getX(It.IsAny<HttpRequestWrapper>())).Returns(someClassInstance);
but it return null, not someClassInstance (by debug i can see it's not null).
what can i do? thanks!

I don't exactly understand why you expecte the result to be "2" nor can i see the declaration of someClassInstance to verify if the Assert should or should not be NULL.
However, I implemented those Methods and wrapped a test around:
using System.Web;
using Moq;
using NUnit.Framework;
public class FooBase
{
public virtual ResultObject getX(HttpRequestBase request)
{
return new ResultObject { Id = 2 };
}
}
public class Foo : FooBase
{
public override ResultObject getX(HttpRequestBase request)
{
return new ResultObject { Id = 4 };
}
}
public class ResultObject
{
public int Id { get; set; }
}
[TestFixture]
public class Test
{
Mock<Foo> mockProvider = new Mock<Foo>();
[Test]
public void FooTest()
{
// Arrange
var fakedResultObject = new ResultObject { Id = 8 };
mockProvider.Setup(x => x.getX(It.IsAny<HttpRequestWrapper>())).Returns(fakedResultObject);
// Act
var result = mockProvider.Object.getX(new HttpRequestWrapper(new HttpRequest("filename", "http://foo.org", "querystring")));
//Assert
Assert.AreEqual(8, result.Id);
}
}

Related

Error CS0118 'TestBuilder' is a namespace but is used like a type

I'm working on Unit test. I create TestBuilder class, where I create method SetupTown method.
When I tried call this method in my main test class - i have error( Error CS0118'TestBuilder' is a namespace but is used like a type). I read about it and recommend to call a class with method. I tried do it, but It doesn't help.
public partial class TownServiceTests
public partial class TownServiceTests
{
private class TestBuilder
{
public Mock<ITownRepository> MockTownRepository { get; set; }
//public Mock<IClientViewModelBuilder> MockClientPropertyModelBuilder { get; set; }
public Mock<IMapper> MockMapper { get; set; }
public TestDataGenerator TestDataGenerator;
private readonly string _jsonDataPath = #"../../../TestData/Town/TownTestData.json";
private string _jsonDataKey;
private TownViewModel Towns { get; set; }
public TestBuilder(string jsonDataKey)
{
MockTownRepository = new Mock<ITownRepository>();
//MockClientPropertyModelBuilder = new Mock<IClientViewModelBuilder>();
MockMapper = new Mock<IMapper>();
TestDataGenerator = new TestDataGenerator(_jsonDataPath);
_jsonDataKey = jsonDataKey;
TestDataGenerator.LoadData(_jsonDataKey);
}
public ITownService Build()
{
return new TownService(MockTownRepository.Object,
MockMapper.Object);
}
public TestBuilder SetupTowns()
{
var towns = TestDataGenerator.GetTestData<Town>(_jsonDataKey, "Towns");
MockTownRepository.Setup(r => r.InsertTown(It.IsAny<string>()))
.ReturnsAsync(towns.FirstOrDefault().Id);
return this;
}
}
}
}
Please check method public TestBuilder SetupTowns
Here my TestClass
[TestClass]
public partial class TownServiceTests
{
[TestMethod]
public async Task ValidInsertTown()
{
var builder = new TestBuilder("Data").SetupTowns; //Problem
var service = builder.Build();
var expectedTowns = builder.TestDataGenerator.GetTestData<Town>("Data", "Towns");
var result = await service.InsertTown(expectedTowns);
Assert.IsNotNull(result);
Assert.IsNull(result);
}
}
Could toy tell me what I do wrong?
Example
public partial class ClientServiceTests
{
private class TestBuilder
{
public Mock<IClientRepository> MockClientRepository { get; set; }
public Mock<IClientViewModelBuilder> MockClientPropertyModelBuilder { get; set; }
public Mock<IMapper> MockMapper { get; set; }
public TestDataGenerator TestDataGenerator;
private readonly string _jsonDataPath = #"../../../TestData/Client/ClientTestData.json";
private string _jsonDataKey;
public TestBuilder(string jsonDataKey)
{
MockClientRepository = new Mock<IClientRepository>();
MockClientPropertyModelBuilder = new Mock<IClientViewModelBuilder>();
MockMapper = new Mock<IMapper>();
TestDataGenerator = new TestDataGenerator(_jsonDataPath);
_jsonDataKey = jsonDataKey;
TestDataGenerator.LoadData(_jsonDataKey);
}
public IClientService Build()
{
return new ClientService(MockClientRepository.Object
, MockClientPropertyModelBuilder.Object
, MockMapper.Object);
}
public TestBuilder SetupClients()
{
var clients = TestDataGenerator.GetTestData<ClientSummary>(_jsonDataKey, "Clients");
MockClientRepository.Setup(r => r.GetClientBySearchCriteria(It.IsAny<string>()))
.ReturnsAsync(clients);
var clientViewModels = TestDataGenerator.GetTestData<ClientViewModel>(_jsonDataKey, "ClientViewModel");
MockClientPropertyModelBuilder.Setup(r => r.GetClientViewModel(clients))
.Returns(clientViewModels);
return this;
}
public TestBuilder SetupInvalidInputClients()
{
MockClientRepository.Setup(r => r.GetClientBySearchCriteria(It.IsAny<string>()))
.ReturnsAsync(new List<ClientSummary>());
MockClientPropertyModelBuilder.Setup(r => r.GetClientViewModel(new List<ClientSummary>()))
.Returns(new List<ClientViewModel>());
return this;
}
}
}
TestClass (here works good)
[TestMethod]
public async Task GetClientBySearchCriteria_ValidInput_ReturnClients()
{
var searchParameter = "1";
var builder = new TestBuilder("Data").SetupClients();
var service = builder.Build();
var expectedClients = builder.TestDataGenerator.GetTestData<ClientSummary>("Data", "Clients");
var result = await service.GetClientBySearchCriteria(searchParameter);
Assert.IsNotNull(result);
Assert.AreEqual(2, result.Count);
Assert.AreEqual(expectedClients.FirstOrDefault().Name, result.FirstOrDefault().Name);
}
namespace of the file
I think, the issue is happened because you have Something.TestBuilder.Something namespace and compiler is trying to use it instead of class.
You have the TestBuilder folder and a few classes inside it. It may be that classes inside TestBuilder folder contains TestBuilder in their namespaces and compiler trying to access this namespace instead of class.

Not able to unit test API controller using moq. Where I'm going wrong?

Controller class
[Route("hollywood/[controller]")]
[ApiController]
public class MoviesController : Controller
{
List<Film> film = new List<Film>()
{
new Film(){id=1,name="The Dark Knight",director="Christopher Nolan", release=2008},
new Film(){id=2,name="300",director="Zack Snyder", release=2007},
new Film(){id=3,name="Titanic",director="James Cameron", release=1997},
};
// GET film/movies
[HttpGet]
public IActionResult Get()
{
// some code
return Json(film);
}
// GET film/movies/{id}
[HttpGet("{id}")]
public IActionResult Get(int id)
{
// some code
return Json(film.FirstOrDefault(x => x.id == id));
}
[HttpPost]
public IActionResult Post([FromBody]Film value)
{
// some code
film.Add(value);
return Json(film);
}
}
Model Class
public class Film
{
public int id { get; set; }
public string name { get; set; }
public string director { get; set; }
public int release { get; set; }
}
Test
[Fact]
public async Task TestGet()
{
List<Film> film = new List<Film>()
{
new Film(){id=1,name="The Dark Knight",director="Christopher Nolan", release=2008},
new Film(){id=2,name="300",director="Zack Snyder", release=2007},
new Film(){id=3,name="Titanic",director="James Cameron", release=1997},
};
// Arrange
string expectedResult = JsonConvert.SerializeObject(film);
var requestUri = new Uri("http://localhost:51867/film/movies");
// Act
var mockHandler = new Mock<MoviesController>();
mockHandler
.Setup(x => x.Get())
.Returns(expectedResult);
var httpClient = new HttpClient(mockHandler.Object);
var result = await httpClient.GetStringAsync(requestUri).ConfigureAwait(false);
// Assert
Assert.Equal(expectedResult, result);
}
I'm performing unit testing using moq. I need to mock the Get/Post calls in Controllers using Moq HttpClient. I'm unable to mock the object. Please let me know what am I doing wrong? Is IActionResult return type causing it to fail? If yes, what else can I use instead of IActionResult?

How can serialize a type that implemented IEnumerable with protobuf if it is in a list itself?

As demonstrated by the following code, even with IgnoreListHandling set to true on the TypeWithEnumerableInterface ProtoContract attribute, it is still detected as a nested list.
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using ProtoBuf;
using ProtoBuf.Meta;
using Assert = NUnit.Framework.Assert;
namespace UnitTests
{
[TestFixture]
public class ProtoListHandling
{
[Test]
public void TestTypeRegistration() //Passes
{
//Arrange
var runtimeTypeModel = TypeModel.Create(); // Don't use the default run time model so the unit test has no side effects
//Act + Assert
Assert.DoesNotThrow(() => runtimeTypeModel[typeof (ITypeInterface)].AddSubType(100, typeof (TypeHoldingOneInstance)));
}
[Test]
public void TestListTypeRegistration() //Fails
{
//Arrange
var runtimeTypeModel = TypeModel.Create(); // Don't use the default run time model so the unit test has no side effects
//Act + Assert
//This test will fail.
Assert.DoesNotThrow(() => runtimeTypeModel[typeof(ITypeInterface)].AddSubType(100, typeof(TypeHoldingListOfInstances)));
}
[ProtoContract]
class TypeHoldingOneInstance : ITypeInterface
{
[ProtoMember(1)]
public TypeWithEnumerableInterface Instance
{
get;
set;
}
}
[ProtoContract]
class TypeHoldingListOfInstances : ITypeInterface
{
[ProtoMember(1)]
public List<TypeWithEnumerableInterface> Instances
{
get;
set;
}
}
[ProtoContract(IgnoreListHandling = true)]
class TypeWithEnumerableInterface : IEnumerable<double>
{
[ProtoMember(1)]
public string ActuallyWantToSerializeThis { get; set; }
public IEnumerator<double> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
interface ITypeInterface
{
}
}
}
Is there a way to persist this without needing to change the implementations of TypeHoldingListOfInstances or TypeWithEnumerableInterface?

JsonSerializer calling container Equals override method

First of all had a good look around and understand override/virtual etc. But haven't found any cases specific to my situation - which I'm sure isn't unique. I want to just make sure the implementation I go with is the right implementation. I have the following code setup to demonstrate my issue:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Sandpit
{
public class Program
{
static void Main()
{
var fixture = new Fixture
{
Name = "Fixture Name",
Participants = new List<Participant> {new Participant {Name = "Participant Name"}}
};
var writer = new StringWriter(new StringBuilder());
var serializer = new JsonSerializer();
serializer.Converters.Add(new StringEnumConverter());
serializer.Serialize(writer, fixture);
Console.Write(writer.ToString());
Console.ReadKey();
}
}
public class Fixture
{
public string Name { get; set; }
public List<Participant> Participants { get; set; }
public override bool Equals(object obj)
{
var fixture = (Fixture)obj;
return fixture.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
public class Participant
{
public string Name { get; set; }
public override bool Equals(object obj)
{
var participant = (Participant)obj;
return participant.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}
Now when this runs I get an exception on var fixture = (Fixture)obj;.
Unable to cast object of type
'System.Collections.Generic.List`1[Sandpit.Participant]' to type
'Sandpit.Fixture'.
I don't understand why it is getting into there. And why this breaks the correct implementation of overridden object methods.
I know that I can fix this by doing public new bool Equals(object obj). Am I doing this right? Also these objects are well integrated into the application I am working on, is there likely to be any side effects to making this change?
Many thanks,
Matt
A small change to your Fixture and Participant classes fixes this:
public class Fixture
{
public string Name { get; set; }
public List<Participant> Participants { get; set; }
public override bool Equals(object obj)
{
var fixture = obj as Fixture;
return fixture == null ? false : fixture.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
public class Participant
{
public string Name { get; set; }
public override bool Equals(object obj)
{
var participant = obj as Participant;
return participant == null ? false : participant.Name == Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
If you are comparing to an element that's of another type, you can be certain that the two are not equal.

Verify that correct method was passed in a function call

My test class takes 2 objects in its constructor, a data loader and a class that consumes the data returned from the data loader.
The data loader interface has 2 functions, LoadCompanies() and LoadEmployees(), both of which take an int parameter and return an IEnumerable.
How can I verify that the method under test passes LoadCompanies() and NOT LoadEmployees() into the data consumer class?
Here is my code:
[TestFixture]
public class TestingFunctionalParameters_UT
{
[Test]
public void Correct_Loader_Method_is_Used()
{
const int userId = 1;
var companies = new[] { "c1", "c2" };
var dataLoader = MockRepository.GenerateMock<ITestDataLoader>();
var dataConsumer = MockRepository.GenerateMock<IDataConsumerClass>();
var testObject = new TestClass(dataLoader, dataConsumer);
dataConsumer.Expect(fc => fc.LoadIt(Arg<Func<IEnumerable<string>>>.Is.TypeOf)).Return(true);
//TODO: validate that correct dataloader function was called...
//dataLoader.Expect(dl => dl.LoadCompanies(userId)).Return(companies);
var result = testObject.Run(userId);
Assert.That(result, Is.True);
dataLoader.VerifyAllExpectations();
dataConsumer.VerifyAllExpectations();
}
}
public class TestClass
{
private readonly ITestDataLoader dataLoader;
private readonly IDataConsumerClass funcClass;
public TestClass(ITestDataLoader dataLoader, IDataConsumerClass funcClass)
{
this.dataLoader = dataLoader;
this.funcClass = funcClass;
}
public bool Run(int userId)
{
Func<IEnumerable<string>> loadFn = () => dataLoader.LoadCompanies(userId);
return funcClass.LoadIt(loadFn);
}
}
public interface ITestDataLoader
{
IEnumerable<string> LoadCompanies(int userId);
IEnumerable<string> LoadEmployees(int userId);
}
public interface IDataConsumerClass
{
bool LoadIt(Func<IEnumerable<string>> load);
}
You could create companies and employees classes
class Company
{
public Company(string name)
{
Name = name;
}
public string Name { get; private set; }
public override string ToString()
{
return Name;
}
}
Do the same for employees and then define your interface like this
public interface ITestDataLoader
{
IEnumerable<Company> LoadCompanies(int userId);
IEnumerable<Employee> LoadEmployees(int userId);
}
Now companies and employees cannot be confused any more.
EDIT:
If you have a lot of cases like that, you could create a common base class
class NamedItem
{
public NamedItem(string name)
{
Name = name;
}
public string Name { get; private set; }
public override string ToString()
{
return Name;
}
}
class Company : NamedItem
{
public Company(string name)
: base(name)
{
}
}
class Employee : NamedItem
{
public Employee (string name)
: base(name)
{
}
}
(Edit: I am assuming that your example is a simplified one, and your actual implementation is an attempt to test a delegate injection pattern)
Maybe you could write your test like this? (Edited to actually compile)
[Test]
public void Correct_Loader_Method_is_Used()
{
const int userId = 1;
var companies = new[] { "c1", "c2" };
var dataLoader = MockRepository.GenerateMock<ITestDataLoader>();
var dataConsumer = MockRepository.GenerateMock<IDataConsumerClass>();
var testObject = new TestClass(dataLoader, dataConsumer);
dataConsumer.Expect(fc => fc.LoadIt(Arg<Func<IEnumerable<string>>>.Matches(x => x().Any()))).Return(true);
//validate that correct dataloader function was called...
dataLoader.Expect(dl => dl.LoadCompanies(userId)).Return(companies);
// Fails if you uncomment this line
//dataLoader.Expect(dl => dl.LoadEmployees(userId)).Return(companies);
var result = testObject.Run(userId);
Assert.That(result, Is.True);
dataLoader.VerifyAllExpectations();
dataConsumer.VerifyAllExpectations();
}
Basically the Matches() constraint will try execute the method, and if it tries to call LoadEmployees(), RhinoMocks will complain because it doesn't have a defined mock.
Update: Handling Action<T> delegates
This might be a little less robust, but for Action<T>s:
public interface IDataConsumerClass
{
bool LoadIt(Func<IEnumerable<string>> load);
bool ExecuteIt<T>(Action<T> execute);
}
//...
dataConsumer.Expect(fc => fc.ExecuteIt(Arg<Action<int>>.Matches(x => ActionWrapper(x, userId)))).Return(true);
//...
private bool ActionWrapper<T>(Action<T> action, T arg)
{
action(arg);
return true;
}

Categories