far jack
far jack

Reputation: 25

using Moq - void return type method Unit test

I am writing unittest for void method actually that method load the collection in ViewData["CityList"] method is

 public void PopulateCityCombo() {
            IEnumerable<Cities> c= service.GetCities();
           ViewData["CityList"] = c.Select(e => new Cities{ ID = e.ID, Name = e.Name});
        }

now i do not know how to unit test using Moq since controller method is void and not returning data, can any one tell i will achive that.

Upvotes: 1

Views: 837

Answers (1)

Jesse
Jesse

Reputation: 8393

On a side note, I would shy away from using ViewData within controller methods as per your example. The ViewData dictionary approach is fast and fairly easy to implement, however it can lead to typo's and errors that are not caught at compile time. An alternative would be to use the ViewModel pattern which allows you to use strongly-typed classes for the specific view you need to expose values or content within. Ultimately giving you type safe and compile time checking along with intellisense.

Switching to the ViewModel pattern would allow you to call the PopulateCityCombo() method from your controller to populate a ViewModel that in turn would passed to the corresponding view.

From there you would need to inject a mock service layer into your controllers constructor from your unit test.

// arrange
var mock = new Mock<servicelayer>();
mock.Setup(x=>x.GetCities()).Returns(expectedData);

var controller = new YourController(mock.Object);

// act
var result = controller.ControllerMethod() as ViewResult;
var resultData = (YourViewModel)result.ViewData.Model;

// assert
// Your assertions

Upvotes: 3

Related Questions