1

I am using Moq for unit testing, and I am trying to write my first unit test. My layers are "Controller=>Service=>Repository".

(I am using unity and repository pattern.)

Whenever I run my unit test, the actual value is always 0 like _service.GetEquipStates().Count() = 0. I do not know where I am doing wrong. Please suggest.

My unit test code is the following one:

private ITestService _service; private Mock<ITestRepository> RepositoryMoc; [TestInitialize] public void Initialize() { RepositoryMoc= new Mock<ITestRepository>(); _service = new TestService(RepositoryMoc.Object) } [TestMethod] public void GetEquipmentState() { var stateList = new[] { new State { ID = 1, Desc= "test" } }; RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList ); Assert.AreEqual(1, _service.GetStates().Count()); } 
1
  • 3
    Please also post the code for TestService.GetStates(). Commented Nov 9, 2011 at 3:06

2 Answers 2

1

Your setup is done for the methode GetState with prameter true.

RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList); 

But your call in the Assert-Statement is for a method GetState without a parameter. Is the method GetState declared with a default parameter or do you have to functions (one with a bool parameter and one without)?

Just make your call in the assert-statement like this and it should work.

Assert.AreEqual(1, _service.GetStates(true).Count()); 
Sign up to request clarification or add additional context in comments.

Comments

1

I have replicated your code in one of my solutions, and the test passes fine.

 private Mock<IAccessor> RepositoryMoc; private Controller _service; [TestMethod] public void TestMethod() { // Arrange _service = new Controller(); RepositoryMoc = new Mock<IAccessor>(); _service.Accessor = RepositoryMoc.Object; var stateList = new[] { new State { ID = 1, Desc = "test" } }; RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList); // Act & Assert Assert.AreEqual(1, _service.GetStates().Count()); } 

Is the code exactly as is in your solution ?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.