Note that there are some explanatory texts on larger screens.

plurals
  1. POUnit Testing with DbContext mock through Service Layer
    text
    copied!<p>I'm a beginner at writing unit tests and I have a test I'm trying to get working. I'll start of by explaining what I'm trying to test.</p> <p>I'm trying to test a method which saves messages in a Mvc 4 project. The method is called <code>SaveMessage</code> and is shown below.</p> <pre><code>namespace ChatProj.Service_Layer { public class UserService : IUserService { public MessageContext messageContext = new MessageContext(); public UserService() { _messageRepository = new MessageRepository(messageContext); } private IMessageRepository _messageRepository; -&gt; public void SaveMessage(Message message) { messageContext.Messages.Add(message); _messageRepository.Save(); } </code></pre> <p>The <code>_messageRepository.Save</code> in the <code>SaveMessage</code> method is implemented in my DAL layer <code>MessageRepository</code> and looks like this:</p> <pre><code>public void Save() { context.SaveChanges(); } </code></pre> <p>This way of saving will seem a bit overcomplicated, but I structured the project this way because I didn't want the service layer (<code>IUserService</code> &amp; <code>UserService</code>) to handle operations that could &amp; should (i think) be handled by the Data Access Layer (<code>IMessageRepository</code> &amp; <code>MessageRepository</code>). </p> <p>Now comes the tricky part. I've been trying to understand how I could unit test this. This is my try:</p> <pre><code>namespace ChatProj.Tests { [TestFixture] class MessageRepositoryTests { [SetUp] public void Setup() { } [Test] public void SaveMessage_SaveWorking_VerifyUse() { //Arrange var userServiceMock = new Mock&lt;UserService&gt;(); var message = new Message { MessageID = 0, Name = "Erland", MessageString = "Nunit Test", MessageDate = DateTime.Now }; var repositoryMock = new Mock&lt;IMessageRepository&gt;(); var contextMock = new Mock&lt;MessageContext&gt;(); MessageRepository messageRepository = new MessageRepository(contextMock.Object); UserService userService = new UserService(); //Act userService.SaveMessage(message); //Assert repositoryMock.Verify(m =&gt; m.Save()); userServiceMock.Verify(m =&gt; m.SaveMessage(message)); } } </code></pre> <p>I get this error: <a href="http://imgur.com/B6OSjLI" rel="nofollow" title="hej">Imgur link</a> , and I'm not quite sure how to solve it. I've tried looking at several other SO posts but I fail to make the test work. </p> <p>So I'm wondering, how do I practically get my Unit Test to work? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload