title: Can I mock a method for an object that's created in a method I'm testing?
body: <pre><code>[TestMethod]
      public void Can_Login_With_Valid_Credentials()
      {
          //Arrange
          Mock&lt;IMembershipRepository&gt; mockRepository = new Mock&lt;IMembershipRepository&gt;();           
  
          Mock&lt;LoginViewModel&gt; mockModel = new Mock&lt;LoginViewModel&gt;();
          mockModel.Setup(x =&gt; x.IsLoggedIn()).Returns(true);            
  
          AccountController target = new AccountController(mockRepository.Object);
  
          //Act
          ActionResult result = target.Login(mockModel.Object);
  
          //Assert
          Assert.IsNotInstanceOfType(result, typeof(ViewResult));
  
      }
  </code></pre>
  
  <p>And ActionResult in the controller</p>
  
  <pre><code>public ActionResult Login(LoginViewModel viewModel)
      {
          string returnUrl = (string)TempData["ReturnUrl"];           
  
          if (ModelState.IsValid)
          {
              LoginViewModel model = new LoginViewModel(repository, viewModel);
  
              if (model.IsLoggedIn())
              {
                  if (String.IsNullOrEmpty(returnUrl)) return RedirectToAction("Index", "Home");
                  else return Redirect(returnUrl);
              }
              else
              {
                  ModelState.AddModelError("Email", "");
                  ModelState.AddModelError("Password", "");
              }
          }
  
          return View(viewModel);
      }
  </code></pre>
  
  <p>I'm having problems with mocking <code>model.IsLoggedIn()</code> in the <code>ActionMethod</code>, and it is probably because I'm creating a new instance of the viewmodel <code>LoginViewModel</code> in that <code>ActionMethod</code>. That is why <code>mockModel.Setup(x =&gt; x.IsLoggedIn()).Returns(true);</code> in the unit test is not caching it because there is a new instance of the class that has that method.</p>
  
  <p>Is there any way i can mock <code>model.IsLoggedIn()</code> in the ActionMethod and make it return <code>true</code>?</p>