How to mock Controller.User using moq

You need to Mock the ControllerContext, HttpContextBase and finally IPrincipal to mock the user property on Controller. Using Moq (v2) something along the following lines should work. [TestMethod] public void HomeControllerReturnsIndexViewWhenUserIsAdmin() { var homeController = new HomeController(); var userMock = new Mock<IPrincipal>(); userMock.Expect(p => p.IsInRole(“admin”)).Returns(true); var contextMock = new Mock<HttpContextBase>(); contextMock.ExpectGet(ctx => ctx.User) .Returns(userMock.Object); var … Read more

How to mock Spring WebFlux WebClient?

We accomplished this by providing a custom ExchangeFunction that simply returns the response we want to the WebClientBuilder: webClient = WebClient.builder() .exchangeFunction(clientRequest -> Mono.just(ClientResponse.create(HttpStatus.OK) .header(“content-type”, “application/json”) .body(“{ \”key\” : \”value\”}”) .build()) ).build(); myHttpService = new MyHttpService(webClient); Map<String, String> result = myHttpService.callService().block(); // Do assertions here If we want to use Mokcito to verify if the … Read more

Mocking generic methods in Moq without specifying T

In Moq 4.13 they introduced the It.IsAnyType type which you can using to mock generic methods. E.g. public interface IFoo { bool M1<T>(); bool M2<T>(T arg); } var mock = new Mock<IFoo>(); // matches any type argument: mock.Setup(m => m.M1<It.IsAnyType>()).Returns(true); // matches only type arguments that are subtypes of / implement T: mock.Setup(m => m.M1<It.IsSubtype<T>>()).Returns(true); … Read more

python mock – patching a method without obstructing implementation

Similar solution with yours, but using wraps: def test_something(self): spud = Potato() with patch.object(Potato, ‘foo’, wraps=spud.foo) as mock: forty_two = spud.foo(n=40) mock.assert_called_once_with(n=40) self.assertEqual(forty_two, 42) According to the documentation: wraps: Item for the mock object to wrap. If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning … Read more

Python mock Patch os.environ and return value

You can try unittest.mock.patch.dict solution. Just call conn with a dummy argument: import mysql.connector import os, urlparse from unittest import mock @mock.patch.dict(os.environ, {“DATABASE_URL”: “mytemp”}, clear=True) # why need clear=True explained here https://stackoverflow.com/a/67477901/248616 # If clear is true then the dictionary will be cleared before the new values are set. def conn(mock_A): print os.environ[“mytemp”] if “DATABASE_URL” … Read more

Mocking Functions Using Python Mock

The general case would be to use patch from mock. Consider the following: utils.py def get_content(): return ‘stuff’ mymodule.py from util import get_content class MyClass(object): def func(self): return get_content() test.py import unittest from mock import patch from mymodule import MyClass class Test(unittest.TestCase): @patch(‘mymodule.get_content’) def test_func(self, get_content_mock): get_content_mock.return_value=”mocked stuff” my_class = MyClass() self.assertEqual(my_class.func(), ‘mocked stuff’) self.assertEqual(get_content_mock.call_count, … Read more

Using mock patch to mock an instance method

To add onto Kit’s answer, specifying a 3rd argument to patch.object() allows the mocked object/method to be specified. Otherwise, a default MagicMock object is used. def fake_bar(self): print “Do something I want!” return True @patch.object(my_app.models.FooClass, ‘bar’, fake_bar) def test_enter_promotion(self): self.client.get(reverse(view)) # Do something I want! Note that, if you specify the mocking object, then the … Read more

How do I mock a class without an interface?

Simply mark any method you need to fake as virtual (and not private). Then you will be able to create a fake that can override the method. If you use new Mock<Type> and you don’t have a parameterless constructor then you can pass the parameters as the arguments of the above call as it takes … Read more

How to check String in response body with mockMvc

You can call andReturn() and use the returned MvcResult object to get the content as a String. See below: MvcResult result = mockMvc.perform(post(“/api/users”).header(“Authorization”, base64ForTestUser).contentType(MediaType.APPLICATION_JSON) .content(“{\”userName\”:\”testUserDetails\”,\”firstName\”:\”xxx\”,\”lastName\”:\”xxx\”,\”password\”:\”xxx\”}”)) .andDo(MockMvcResultHandlers.print()) .andExpect(status().isBadRequest()) .andReturn(); String content = result.getResponse().getContentAsString(); // do what you will