JMock map expectations - dictionary

I have a dependency with a method that takes a Map as an argument.
public interface Service {
void doSomething(Map<String, String> map);
}
I'd like to write an assertion that this dependency is called with appropriate map contents. Something like this:
#RunWith(JMock.class)
public class MainTest {
private Mockery context = new Mockery();
private Service service = context.mock(Service.class);
private Main main = new Main(service);
#Test
public void test() {
context.checking(new Expectations(){{
oneOf(service).doSomething(with(hasEntry("test", "test")));
}});
main.run();
}
}
Unfortunately, this fails to compile, since hasEntry has wildcards in map generic parameters:
public static <K, V> org.hamcrest.Matcher<java.util.Map<? extends K, ? extends V>> hasEntry(K key, V value);
Is there any way to write a JMock expectaion for map contents?

There isn't a good answer to this as we hit the limits of Java generics. There's a tension between the generics we need for jMock and what we need for assertThat()
I tend to add a helper method, with an expressive name, to force the types.
#Test public void test() {
context.checking(new Expectations(){{
oneOf(service).doSomething(with(mapIncluding("test", "test")));
}});
main.run();
}
#SuppressWarnings({"unchecked", "rawtypes"})
private Matcher<Map<String, String>> mapIncluding(String key, String value) {
return (Matcher)Matchers.hasEntry(key, value);
};
Yes, this is pig-ugly. I can only apologise that this is the best we appear to be able to do. That said, it's rare that I have to go as far as turning off the types, I can give it a name that's meaningful in the domain, and I've localised the unchecking to the helper method.

I ended up creating a method specify() that allows downcasting of generic matchers to more specific ones
public static <T> Matcher<T> specify(final Matcher<? super T> matcher) {
return new TypeSafeMatcher<T>() {
#Override
protected boolean matchesSafely(T item) {
return matcher.matches(item);
}
#Override
public void describeTo(Description description) {
matcher.describeTo(description);
}
};
}
Using this method I can downcast any existing generic matcher, like hasEntry()
public <K, V> Matcher<Map<? extends K, ? extends V>> hasEntry(K key, V value)
to a more specific one in a generic-safe manner, like this:
private static <K,V> Matcher<Map<K, V>> aMapHavingEntry(K key, V value) {
return specify(hasEntry(key, value));
}
Now I can use this specific matcher as an expectation parameter:
context.checking(new Expectations() {{
oneOf(service).doSomething(with(aMapHavingEntry("test", "test")));
}});
Using specify() method I created a bunch of specific matchers for most popular interfaces: Map, Collection, List, Set, like:
private static <K,V> Matcher<Map<K, V>> aMapHavingEntry(K key, V value) {
return specify(hasEntry(key, value));
}
private static <K> Matcher<Collection<K>> aCollectionContainingInAnyOrder(K... items) {
return specify(containsInAnyOrder(items));
}
I also suggested adding the same functionality to JMock, though all I got was silence.

Related

Leveraging user context in an IHostedService via DI

I have a series of class libraries that are used in asp.net-core middleware, and in an IHostedService.
To fetch the user context, I can inject IHttpContextAccessor to grab the HttpContext user:
public class MyLibrary
{
public MyLibrary(IHttpContextAccessor accessor)
{
// set the accessor - no problem
}
public async Task DoWorkAsync(SomeObject payload)
{
// get the user from the accessor
// do some work
}
}
To be a little more abstract, I have an IUserAccessor with an HttpUserAccessor implementation:
public class HttpUserAccessor: IUserAccessor
{
IHttpContextAccessor _httpaccessor;
public HttpUserAccessor(IHttpContextAccessor accessor)
{
_httpaccessor = accessor;
}
public string GetUser()
{
// return user from _httpaccessor
}
}
and then MyLibrary does not need an IHttpContextAccessor dependency:
public class MyLibrary
{
public MyLibrary(IUserAccessor accessor)
{
// set the accessor - no problem
}
public async Task DoWorkAsync(SomeObject payload)
{
// get the user from the accessor
// do some work
}
}
My IHostedService is popping message from a queue, where the message includes:
a user context, and
a serialized SomeObject to pass to MyLibrary.DoWorkAsync
So, something like:
public class MyHostedService : IHostedService
{
IServiceScopeProvider _serviceScopeFactory;
public MyHostedService(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = servicesScopeFactory;
}
public Task StartAsync(CancellationToken cancellationToken)
{ ... }
public Task StopAsync(CancellationToken cancellationToken)
{ ... }
public async Task ExecuteAsync(CancellationToken stoppingToken)
{
foreach (var message in queue)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
// todo: tell IUserAccessor what message.User is!
var payload = // create a SomeObject from the queue message
var mylibrary = _services.GetRequiredService<MyLibrary>();
await myLibrary.DoWorkAsync(payload);
}
}
}
}
So, my question is, how does MyHostedService store message.User in such a way that a custom IUserAccessor can access it in a thread-safe manner via DI?
how does MyHostedService store message.User in such a way that a custom IUserAccessor can access it in a thread-safe manner via DI?
The thing you're looking for is AsyncLocal<T> - it's like a thread-local variable but scoped to a (possibly asynchronous) code block instead of a thread.
I tend to prefer a "provider" + "accessor" pairing for this: one type that provides the value, and a separate type that reads the value. This is logically the same thing as a React Context in the JS world, though the implementation is quite different.
One tricky thing about AsyncLocal<T> is that you need to overwrite its value on any change. In this case, that's not really a problem (no message processing will want to update the "user"), but in the general case it's important to keep in mind. I prefer storing immutable types in the AsyncLocal<T> to ensure they aren't mutated directly instead of overwriting the value. In this case, your "user" is a string, which is already immutable, so that's perfect.
First, you'll need to define the actual AsyncLocal<T> to hold the user value and define some low-level accessors. I strongly recommend using IDisposable to ensure the AsyncLocal<T> value is unset properly at the end of the scope:
public static class AsyncLocalUser
{
private static AsyncLocal<string> _local = new AsyncLocal<string>();
private static IDisposable Set(string newValue)
{
var oldValue = _local.Value;
_local.Value = newValue;
// I use Nito.Disposables; feel free to replace with another IDisposable implementation.
return Disposable.Create(() => _local.Value = oldValue);
}
private static string Get() => _local.Value;
}
Then you can define a provider:
public static class AsyncLocalUser
{
... // see above
public sealed class Provider
{
public IDisposable SetUser(string value) => Set(value);
}
}
and the accessor is similarly simple:
public static class AsyncLocalUser
{
... // see above
public sealed class Accessor : IUserAccessor
{
public string GetUser() => Get();
}
}
You'll want to set up your DI to point IUserAccessor to AsyncLocalUser.Accessor. You can also optionally add AsyncLocalUser.Provider to your DI, or you can just create it directly.
Usage would go something like this:
foreach (var message in queue)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var userProvider = new AsyncLocalUser.Provider(); // (or get it from DI)
using (userProvider.SetUser(message.User))
{
var payload = // create a SomeObject from the queue message
var mylibrary = _services.GetRequiredService<MyLibrary>();
await myLibrary.DoWorkAsync(payload);
}
}
}

Is there a better method than ListWrapper to bind a List<T> in a Spring MVC method?

In order to retrieve a list in a Spring MVC application I would like to write something like:
public String myMethod(#RequestParam("foo") List<FooUi> foos)
But the only solution I've found so far is the following :
public String myMethod(FooListWrapperUi fooListWrapperUi)
I don't like this solution because I have to write a wrapper each time I need to retrieve a list. In this example, the wrapper is the following :
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class FooListWrapperUi
{
private ArrayList<FooUi> fooList;
}
So my question is, is it possible to use something like the first solution or is it impossible and I need to write a wrapper?
Thanks.
You can accommodate your use case by creating your own HandlerMethodArgumentResolver:
public class FooUiResolver implements HandlerMethodArgumentResolver {
#Override
public boolean supportsParameter(MethodParameter methodParameter) {
return (methodParameter.getParameterType().equals(FooUi.class) ||
(methodParameter instanceof Collection<?> && ((ParameterizedType) methodParameter.getParameterType().getGenericSuperclass()).getActualTypeArguments()[0] == FooUi.class));
}
#Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) throws Exception {
// Create instances of FooUi by accessing requests parameters in nativeWebRequest.getParameterMap()
}
}
The actual implementation will depend on how you would create one or more FooUi instances from the request parameters or body. You then need to register FooUiResolver in your servlet config:
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers){
argumentResolvers.add(new FooUiResolver());
super.addArgumentResolvers(argumentResolvers);
}
Once registered, you can use FooUi in your controller method arguments without RequestParam or any other annotation:
#RequestMapping(value = "/foo")
public String myMethod(List<FooUi> foos){}

Mocking a protected generic method with Moq

To mock a protected virtual (non-generic) method in Moq is easy:
public class MyClass
{
....
protected virtual int MyMethod(Data data){..}
}
And to mock it:
myMock.Protected().Setup<int>("MyMethod", ItExpr.Is<Data>( ...
I could not find a way to use the same technique if the protected method is generic, like:
protected virtual int MyMethod<T>(T data)
Any idea how to do it, besides using a wrapper class to override that method, is highly appreciated.
I've checked the source and it seems mocking protected generic methods with Moq is not supported:
The Protected() method creates an instance of a class ProtectedMock<T> which uses the following method to get the method that you want to mock:
private static MethodInfo GetMethod(string methodName, params object[] args)
{
return typeof(T).GetMethod(
methodName,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
null,
ToArgTypes(args),
null);
}
It uses Type.GetMethod to get the method for mocking, but GetMethod (although MSDN states differently) don't play nice with generics, see:
GetMethod for generic method
Get a generic method without using GetMethods
Side note:
In my opinion mocking a protected member is a code smell, and I would rather try to avoid it anyway with refactoring my design (beside that it's not supported in Moq).
It can be done since Moq 4.13 (2019-09-01) by using As for protected methods and It.IsAnyType for generic type arguments:
classUnderTest.Protected().As<IMyMethodMock>().Setup(x => x.MyMethod(It.IsAny<It.IsAnyType>())).Returns(...);
And create the following interface for the mocking method:
public interface IMyMethodMock
{
int MyMethod<T>(T data);
}
Full example:
[TestClass]
public class MockingProtectedGenericFixture
{
[TestMethod]
public void test()
{
// Arrange
var classUnderTest = new Mock<MyClass>();
classUnderTest.Protected().As<IMyMethodMock>().Setup(x => x.MyMethod(It.IsAny<It.IsAnyType>())).Returns(2);
// Act
var resForStringData = classUnderTest.Object.GetNumber("DataString");
var resForBooleanData = classUnderTest.Object.GetNumber(true);
// Assert
Assert.AreEqual(2, resForStringData);
Assert.AreEqual(2, resForBooleanData);
}
}
public class MyClass
{
public int GetNumber<T>(T data)
{
return MyMethod(data);
}
protected virtual int MyMethod<T>(T data)
{
return 1;
}
}
public interface IMyMethodMock
{
int MyMethod<T>(T data);
}

Factory Method Pattern clarification

My understanding of Factory Method Pattern is (Correct me if i am wrong)
Factory Method Pattern
"Factory Method allow the client to delegates the product creation (Instance Creation) to the subclass".
There are two situation in which we can go for creating Factory Method pattern.
(i) When the client is restricted to the product (Instance) creation.
(ii) There are multiple products available.But a decision to be made which product instance
need to be returned.
If you want to create Abstract Method pattern
You need to have abstract product
Concrete Product
Factory Method to return the appropriate product.
Example :
public enum ORMChoice
{
L2SQL,
EFM,
LS,
Sonic
}
//Abstract Product
public interface IProduct
{
void ProductTaken();
}
//Concrete Product
public class LinqtoSql : IProduct
{
public void ProductTaken()
{
Console.WriteLine("OR Mapping Taken:LinqtoSql");
}
}
//concrete product
public class Subsonic : IProduct
{
public void ProductTaken()
{
Console.WriteLine("OR Mapping Taken:Subsonic");
}
}
//concrete product
public class EntityFramework : IProduct
{
public void ProductTaken()
{
Console.WriteLine("OR Mapping Taken:EntityFramework");
}
}
//concrete product
public class LightSpeed : IProduct
{
public void ProductTaken()
{
Console.WriteLine("OR Mapping Taken :LightSpeed");
}
}
public class Creator
{
//Factory Method
public IProduct ReturnORTool(ORMChoice choice)
{
switch (choice)
{
case ORMChoice.EFM:return new EntityFramework();
break;
case ORMChoice.L2SQL:return new LinqtoSql();
break;
case ORMChoice.LS:return new LightSpeed();
break;
case ORMChoice.Sonic:return new Subsonic();
break;
default: return null;
}
}
}
**Client**
Button_Click()
{
Creator c = new Creator();
IProduct p = c.ReturnORTool(ORMChoice.L2SQL);
p.ProductTaken();
}
Is my understanding of Factory Method is correct?
What you have there is actually more of an Abstract Factory Pattern, only that you factory (Creator) is not abstract. The factor method pattern is specifically useful for subclassing:
class A {
public:
A() : m_Member( GetMember() )
{
}
protected:
virtual ISomeInterface * GetMember() { // default impl here }
private:
ISomeInterface * m_Member;
}
Now subclasses of A can override GetMember to make the superclass use a specific implementation of ISomeInterface.
Define an interface for creating an
object, but let subclasses decide
which class to instantiate. Factory
Method lets a class defer
instantiation to subclasses.
more details and example there: http://www.dofactory.com/Patterns/PatternFactory.aspx
Yes, that appears to be a correct way to implement this, although pretty simplistic. In reality, you may want to account for the passing-in of various parameters that may not always be consistent across all types. Dictionaries/Lists/Hashtables/etc. are useful for this, as is serialized items and/or XML and other dynamicish things.

Grails bind request parameters to enum

My Grails application has a large number of enums that look like this:
public enum Rating {
BEST("be"), GOOD("go"), AVERAGE("av"), BAD("ba"), WORST("wo")
final String id
private RateType(String id) {
this.id = id
}
static public RateType getEnumFromId(String value) {
values().find {it.id == value }
}
}
If I have a command object such as this:
class MyCommand {
Rating rating
}
I would like to (for example) automatically convert a request parameter with value "wo" to Rating.WORST.
The procedure for defining custom converters is described here (in the context of converting Strings to Dates). Although this procedure works fine, I don't want to have to create a class implementing PropertyEditorSupport for each of my enums. Is there a better alternative?
I found a solution I'm pretty happy with.
Step 1: Create an implementation of PropertyEditorSupport to convert text to/from the relevant Enum
public class EnumEditor extends PropertyEditorSupport {
private Class<? extends Enum<?>> clazz
public EnumEditor(Class<? extends Enum<?>> clazz) {
this.clazz = clazz
}
public String getAsText() {
return value?.id
}
public void setAsText(String text) {
value = clazz.getEnumFromId(text)
}
}
Step 2: Define a class that registers EnumEditor as a converter for the various enum classes. To change the list of enum classes that are bindable by id, just modify BINDABLE_ENUMS
public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
private static final String REQUIRED_METHOD_NAME = 'getEnumFromId'
// Add any enums that you want to bind to by ID into this list
private static final BINDABLE_ENUMS = [Rating, SomeOtherEnum, SomeOtherEnum2]
public void registerCustomEditors(PropertyEditorRegistry registry) {
BINDABLE_ENUMS.each {enumClass ->
registerEnum(registry, enumClass)
}
}
/**
* Register an enum to be bound by ID from a request parameter
* #param registry Registry of types eligible for data binding
* #param enumClass Class of the enum
*/
private registerEnum(PropertyEditorRegistry registry, Class<? extends Enum<?>> enumClass) {
boolean hasRequiredMethod = enumClass.metaClass.methods.any {MetaMethod method ->
method.isStatic() && method.name == REQUIRED_METHOD_NAME && method.parameterTypes.size() == 1
}
if (!hasRequiredMethod) {
throw new MissingMethodException(REQUIRED_METHOD_NAME, enumClass, [String].toArray())
}
registry.registerCustomEditor(enumClass, new EnumEditor(enumClass))
}
}
Step 3: Make Spring aware of the registry above by defining the following Spring bean in grails-app/conf/spring/resources.grooovy
customPropertyEditorRegistrar(CustomPropertyEditorRegistrar)
So the default Databinding binds on the Enum name and not a separately defined property of the Enum. You can either create your own PropertyEditor as you have mentioned or do a work-around similar to this:
class MyCommand {
String ratingId
Rating getRating() {
return Rating.getEnumFromId(this.ratingId)
}
static constraints = {
ratingId(validator:{val, obj -> Rating.getEnumFromId(val) != null })
}
}

Resources