Patterns or practices for unit testing methods that call a static method

Using dependency injection (either option 2 or 4) is definitely my preferred method of attacking this. Not only does it make testing easier it helps to separate concerns and keep classes from getting bloated. A clarification I need to make though is it is not true that static methods are hard to test. The problem … Read more

How do I unit test spring security @PreAuthorize(hasRole)?

UPDATE Spring Security 4 provides comprehensive support for integrating with MockMvc. For example: import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration public class SecurityMockMvcTests { @Autowired private WebApplicationContext context; private MockMvc mvc; @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); } @Test public void withUserRequestPostProcessor() { mvc .perform(get(“/admin”).with(user(“admin”).roles(“USER”,”ADMIN”))) … } @WithMockUser(roles=”ADMIN”) @Test public void … Read more

How to mock a dictionary in Python

How to mock a dictionary in Python is a good/direct question someone else can search, so: I suggest MagicMock instead of Mock Overload the __getitem__ from unittest.mock import MagicMock m = MagicMock() d = {‘key_1’: ‘value’} m.__getitem__.side_effect = d.__getitem__ # dict behaviour m[‘key_1’] # => ‘value’ m[‘key_2’] # => raise KeyError # mock behaviour m.foo(42) … Read more

How to inject a Mock in a Spring Context [duplicate]

Yes, you are on the right track, putting a mock @Bean in a @Configuration class is one approach, and I’ll describe my experience: The trick is that you need to use a different set of .xml files purely for testing which exclude the live versions of those beans. @ContextConfiguration(locations = {“context1-test.xml”, “context2-test.xml”, …}) And the … Read more

How do I mock a django signal handler?

Possibly a better idea is to mock out the functionality inside the signal handler rather than the handler itself. Using the OP’s code: @receiver(post_save, sender=User, dispatch_uid=’myfile.signal_handler_post_save_user’) def signal_handler_post_save_user(sender, *args, **kwargs): do_stuff() # <– mock this def do_stuff(): … do stuff in here Then mock do_stuff: with mock.patch(‘myapp.myfile.do_stuff’) as mocked_handler: self.assert_equal(mocked_handler.call_count, 1)

Mocking __init__() for unittesting

Instead of mocking, you could simply subclass the database class and test against that: class TestingDatabaseThing(DatabaseThing): def __init__(self, connection): self.connection = connection and instantiate that class instead of DatabaseThing for your tests. The methods are still the same, the behaviour will still be the same, but now all methods using self.connection use your test-supplied connection … Read more