Clojure call java method with interface parameters - clojure

Can I call java method with interface as parameters?
When I call java method can I cast it into interface before I use it as paramaters?
Here's my sample code.
// Java code
interface IFace {
String message();
}
class A implements IFace {
#Override message () { return "Hello A!"};
}
class B implements IFace {
#Override message () { return "Hello B!"};
}
class PrintHello {
static void print (IFace msg) {
if (msg instanceof A) { ... } else { ... }
}
}
; Clojure code
(def a (A.))
(. PrintHello (print a))

Changed Java code works for me (see comments):
public interface IFace {
String message();
}
// Class should be public
public class A implements IFace {
#Override
public String message() {
return "Hello A!";
}
}
// Class should be public
public class B implements IFace {
#Override
public String message() {
return "Hello B!";
}
}
public class PrintHello {
// Method should be public
static public void print (IFace msg) {
msg.message();
}
}
(def a (A.))
(PrintHello/print a)

Here is a slightly cleaner version of your code:
~/expr/demo > d **/*.java
-rw-rw-r-- 1 alan alan 136 May 5 13:42 src/java/demo/Bart.java
-rw-rw-r-- 1 alan alan 120 May 5 13:42 src/java/demo/Homer.java
-rw-rw-r-- 1 alan alan 62 May 5 13:37 src/java/demo/Msg.java
> more **/*.java
::::::::::::::
Msg.java
::::::::::::::
package demo;
public interface Msg {
public String msg();
}
::::::::::::::
Bart.java
::::::::::::::
package demo;
public class Bart implements Msg {
public Bart() {}
public String msg() {
return "Don't have a cow, man!";
}
}
::::::::::::::
Homer.java
::::::::::::::
package demo;
public class Homer implements Msg {
public Homer() {}
public String msg() {
return "Doh!";
}
}
Clojure code:
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test)
(:import [demo Msg Homer Bart]))
(dotest
(let [homer (Homer.)
bart (Bart.)]
(spyx (.msg homer))
(spyx (.msg bart))))
with result:
-------------------------------
Clojure 1.10.1 Java 14
-------------------------------
lein test tst.demo.core
(.msg homer) => "Doh!"
(.msg bart) => "Don't have a cow, man!"
Please see this template project and the documentation resources list.

Related

How to write Unit test for ViewModel that contains RxJava/RxAndroid

I'm trying to refactor one pretty old project, so I started implementing new architecture (MVVM) with Dagger2, RxJava, RxAndroid... Now everything is connected and working fine, now the problem is, I have no idea how to write a Unit test for my ViewModel..
I want to start with Login screen first, so I created a LoginViewModel, but first let me show you what I did..
I have a DataModule that provides 2 classes, RestApiRepository and ViewModelFactory. RestApiRepository looks like this:
public class RestApiRepository {
private RestClient restClient;
public RestApiRepository(RestClient restClient) {
this.restClient = restClient;
}
public Observable<AuthResponseEntity> authenticate(String header, AuthRequestEntity requestEntity) {
return restClient.postAuthObservable(header, requestEntity);
}
}
Rest client with api call for login:
public interface RestClient {
#POST(AUTH_URL)
Observable<AuthResponseEntity> postAuthObservable(#Header("Authorization") String authKey, #Body AuthRequestEntity requestEntity);
}
Second class from DataModule is ViewModelFactory:
#Singleton
public class ViewModelFactory extends ViewModelProvider.NewInstanceFactory implements ViewModelProvider.Factory {
private RestApiRepository repository;
#Inject
public ViewModelFactory(RestApiRepository repository) {
this.repository = repository;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(LoginViewModel.class)) {
return (T) new LoginViewModel(repository);
}
throw new IllegalArgumentException("Unknown class name");
}
}
And finally, LoginViewModel:
public class LoginViewModel extends ViewModel {
private final CompositeDisposable disposable = new CompositeDisposable();
private final MutableLiveData<AuthResponseEntity> responseLiveData = new MutableLiveData<>();
private RestApiRepository restApiRepository;
private SchedulerProvider provider;
public LoginViewModel(RestApiRepository restApiRepository, SchedulerProvider provider) {
this.restApiRepository = restApiRepository;
this.provider = provider;
}
public MutableLiveData<AuthResponseEntity> getResponseLiveData() {
return responseLiveData;
}
#Override
protected void onCleared() {
disposable.clear();
}
public void auth(String token, AuthRequestEntity requestEntity) {
if (token != null && requestEntity != null) {
disposable.add(restApiRepository.authenticate(token, requestEntity)
.subscribeOn(provider.io())
.observeOn(provider.ui())
.subscribeWith(new DisposableObserver<AuthResponseEntity>() {
#Override
public void onNext(AuthResponseEntity authResponseEntity) {
responseLiveData.setValue(authResponseEntity);
}
#Override
public void onError(Throwable e) {
AuthResponseEntity authResponseEntity = new AuthResponseEntity();
authResponseEntity.setErrorMessage(e.getMessage());
responseLiveData.setValue(authResponseEntity);
}
#Override
public void onComplete() {
}
}
));
}
}
}
So, I'm sure everything is connected well, I can successfuly login...
For the RxAndroid test issues, I found somewhere that I have to use this Scheduler provider like this:
public class AppSchedulerProvider implements SchedulerProvider {
public AppSchedulerProvider() {
}
#Override
public Scheduler computation() {
return Schedulers.trampoline();
}
#Override
public Scheduler io() {
return Schedulers.trampoline();
}
#Override
public Scheduler ui() {
return Schedulers.trampoline();
}
}
Below is my LoginViewModelTest class, but I don't know how to handle RxJava/RxAndroid inside the tests..
#RunWith(MockitoJUnitRunner.class)
public class LoginViewModelTest {
#Mock
private RestApiRepository restApiRepository;
#Mock
private MutableLiveData<AuthResponseEntity> mutableLiveData;
private LoginViewModel loginViewModel;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
AppSchedulerProvider schedulerProvider = new AppSchedulerProvider();
loginViewModel = Mockito.spy(new LoginViewModel(restApiRepository, schedulerProvider));
}
#Test
public void authenticate_error() {
String token = "token";
AuthRequestEntity requestEntity = Mockito.mock(AuthRequestEntity.class);
Mockito.doReturn(Observable.error(new Throwable())).when(restApiRepository).authenticate(token, requestEntity);
loginViewModel.auth(token, requestEntity);
AuthResponseEntity responseEntity = Mockito.mock(AuthResponseEntity.class);
responseEntity.setErrorMessage("Error");
Mockito.verify(mutableLiveData).setValue(responseEntity);
}
}
So, I wanted to write a test for failed case when onError is called, but when I run it, I get this error:
exclude patterns:io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
You can mock the behaviour of restApiRepository:
Mockito.when(restApiRepository.authenticate(token, requestEntity)).thenReturn(Observable.error(error));
and verify that responseLiveData.setValue is being called with the appropriate parameters

How do I unit test handlers with NServiceBus?

This should be simple and I'm probably missing something. I'm working from here: http://support.nservicebus.com/customer/portal/articles/856297-unit-testing
The following always fails:
[TestFixture]
public class MyTestFixture
{
[Test]
public void RoundTrip() {
Test.Initialize();
var correlationId = Guid.NewGuid();
Test.Handler(bus => new MyHandler(bus))
.ExpectReply<IEventThatHappened>(m => m.CorrelationId == correlationId)
.OnMessage<MyCommand>(m => new MyCommand(correlationId));
}
}
public interface IEventThatHappened : IEvent
{
Guid CorrelationId { get; set; }
}
public class MyCommand : ICommand
{
public Guid CorrelationId { get; private set; }
public MyCommand(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class MyHandler : IHandleMessages<MyCommand>
{
private readonly IBus _bus;
public MyHandler(IBus bus) {
if (bus == null) {
throw new ArgumentNullException("bus");
}
_bus = bus;
}
public void Handle(MyCommand message) {
_bus.Send<IEventThatHappened>(m => m.CorrelationId = message.CorrelationId);
}
}
If I set a breakpoint inside my handler, the message.CorrelationId == Guid.Empty. The exception thrown during the test is:
System.Exception : ExpectedReplyInvocation not fulfilled.
Calls made:
SendInvocation
I've tried using bus.Send, bus.Publish, bus.Reply but each one fails with the corresponding Expected*Invocation .
Why is the message.CorrelationId == Guid.Empty instead of the value I supplied? Why doesn't Test.Handler<> detect that I've called Send/Reply/Publish in my handler?
NOTE: Using NServiceBus 3.3 from Nuget.
There are a couple issues here.
In your handler, you are trying to Bus.Send() an event (the IEventThatHappened implements IEvent and is even named like an event), which is not allowed. Commands are Sent, Events are Published.
Your test is using ExpectReply, which is what you would expect if the handler were doing Bus.Reply(). Assuming you fixed #1, I believe you would be looking for .ExpectPublish().
So first you need to work out what it really is you're meaning to do!
You need to Reply instead of Send!
Here is the test that passes:
[TestFixture]
public class MyTestFixture
{
[Test]
public void RoundTrip()
{
Test.Initialize();
var correlationId = Guid.NewGuid();
var myCommand = new MyCommand(correlationId);
Test.Handler(bus => new MyHandler(bus))
.ExpectReply<IEventThatHappened>(m => m.CorrelationId == correlationId)
.OnMessage(myCommand);
}
}
public interface IEventThatHappened : IEvent
{
Guid CorrelationId { get; set; }
}
public class MyCommand : ICommand
{
public Guid CorrelationId { get; private set; }
public MyCommand(Guid correlationId)
{
CorrelationId = correlationId;
}
}
public class MyHandler : IHandleMessages<MyCommand>
{
private readonly IBus _bus;
public MyHandler(IBus bus)
{
if (bus == null)
{
throw new ArgumentNullException("bus");
}
_bus = bus;
}
public void Handle(MyCommand message)
{
_bus.Reply<IEventThatHappened>(m => m.CorrelationId = message.CorrelationId);
}
}

Unit testing of WF code activity

I have created coded activity and now I want to unit test it, but I do not know how.
Any example will be appreciated.
My simple example is below.
public sealed class ParameterActivity : CodeActivity
{
public InArgument<int> Argument1 { get; set; }
public InArgument<int> Argument2 { get; set; }
public OutArgument<int> Result { get; set; }
protected override void Execute(CodeActivityContext context)
{
var a = context.GetValue(Argument1);
var b = context.GetValue(Argument2);
context.SetValue(Result, a + b);
}
}
First of all, in case your activity returns a single value, just inherit from CodeActivity<TResult> and easily override Execute() with TResult as return type. Moreover, you've already available an OutArgument<TResult> Result.
public sealed class ParameterActivity : CodeActivity<int>
{
public InArgument<int> Argument1 { get; set; }
public InArgument<int> Argument2 { get; set; }
protected override int Execute(CodeActivityContext context)
{
var a = Argument1.Get(context);
var b = Argument2.Get(context);
return a + b;
}
}
That being said, WorkflowInvoker is the way to go to unit test almost all your activities. Taking above custom code activity as example:
[TestFixture]
public sealed class ParameterActivityTests
{
[Test]
public void ParameterActivity_Test()
{
var activity = new ParameterActivity();
var input1 = new Dictionary<string, object>
{
{ "Argument1", 10 },
{ "Argument2", 5 }
};
var input2 = new Dictionary<string, object>
{
{ "Argument1", -13 },
{ "Argument2", 3 }
};
var output1 = WorkflowInvoker.Invoke<int>(activity, input1);
var output2 = WorkflowInvoker.Invoke<int>(activity, input2);
Assert.That(output1, Is.EqualTo(15));
Assert.That(output2, Is.EqualTo(-10));
}
}
Rather than WorkflowInvoker you can also use WorkflowApplication but for unit testing that doesn't seem at all necessary when you just want to quickly invoke short-lived workflows for them to do "their thing" and return. Unless you want to test more elaborate stuff like asynchronous workflows and/or bookmarks.
You'll also want to check Microsoft.Activities.UnitTesting.

Unit Test a CSLA Asynchronous Validation Rule

I have a validation rule on a CSLA Business Base stereotyped class. I'm having trouble figuring out how to unit test the validation rule as it includes an asynchronous callback lambda expression. Here's some example code:
using System;
using System.Collections.Generic;
using Csla;
using Csla.Validation;
namespace UnitTestCSLAAsyncValidationRule
{
public class BusinessObject : BusinessBase<BusinessObject>
{
protected static PropertyInfo<string> CodeProperty = RegisterProperty<string>(p => p.Code);
public string Code
{
get { return GetProperty(CodeProperty); }
set { SetProperty(CodeProperty, value); }
}
protected override void AddBusinessRules()
{
ValidationRules.AddRule(CodeValidator, new AsyncRuleArgs(CodeProperty));
}
public static void CodeValidator(AsyncValidationRuleContext context)
{
var code = (string) context.PropertyValues["Code"];
CodeList codeList;
CodeList.GetCodeList((o, l) =>
{
codeList = l.Object;
if (codeList.Contains(code))
{
context.OutArgs.Result = false;
context.OutArgs.Description = "Code already in use.";
}
else
{
context.OutArgs.Result = true;
}
});
context.Complete();
}
}
public class CodeList : List<string>
{
public static void GetCodeList(EventHandler<DataPortalResult<CodeList>> handler)
{
DataPortal<CodeList> dp = new DataPortal<CodeList>();
dp.FetchCompleted += handler;
dp.BeginFetch();
}
private void DataPortal_Fetch()
{
// some existing codes..
Add("123");
Add("456");
}
}
}
I would like to test this with a test similar to the following:
using NUnit.Framework;
namespace UnitTestCSLAAsyncValidationRule.Test
{
[TestFixture]
public class BusinessObjectTest
{
[Test]
public void CodeValidationTest()
{
var bo = new BusinessObject();
bo.Code = "123";
Assert.IsNotEmpty(bo.BrokenRulesCollection);
}
}
}
However, the test Assert runs before the async callback. Is this something UnitDriven could help with? I've had a look at it but can't see how to use it in this scenario.
Thanks,
Tom
Answered by JonnyBee on http://forums.lhotka.net/forums/p/10023/47030.aspx#47030:
using NUnit.Framework;
using UnitDriven;
namespace UnitTestCSLAAsyncValidationRule.Test
{
[TestFixture]
public class BusinessObjectTest : TestBase
{
[Test]
public void CodeValidationTest()
{
UnitTestContext context = GetContext();
var bo = new BusinessObject();
bo.ValidationComplete += (o, e) =>
{
context.Assert.IsFalse(bo.IsValid);
context.Assert.Success();
//Assert.IsNotEmpty(bo.BrokenRulesCollection);
};
bo.Code = "123";
context.Complete();
}
}
}
Please not there was a small bug in my validation rule method - the call to AsyncValidationRuleContext.Complete() needs to be inside the lambda.
Thanks,
Tom

Fluent NHibernate PersistenceSpecification can't test a collection of strings

I'm using Fluent NHibernate to map a a class that has a collection of strings like this:
public class Foo {
public virtual ICollection<string> Strings { get; set; }
}
public class FooMap : ClassMap<Foo> {
public FooMap() { HasMany(f => f.Strings).Element("SomeColumnName"); }
}
When I write a unit test using the PersistenceSpecification class included in the FNH package, it fails:
[TestMethod]
public void CanMapCollectionOfStrings() {
var someStrings = new List<string> { "Foo", "Bar", "Baz" };
new PersistenceSpecification<Foo>(CurrentSession)
.CheckList(x => x.Strings, someStrings) // MappingException
.VerifyTheMappings();
}
This test throws NHibernate.MappingException: No persister for: System.String when calling CheckList(). However, if I try to persist the object myself, it works just fine.
[TestMethod]
public void CanPersistCollectionOfStrings() {
var foo = new Foo {
Strings = new List<string> { "Foo", "Bar", "Baz" };
};
CurrentSession.Save(foo);
CurrentSession.Flush();
var savedFoo = CurrentSession.Linq<Foo>.First();
Assert.AreEqual(3, savedFoo.Strings.Count());
// Test passes
}
Why is the first unit test failing?
CheckComponentList method is probably the right way in this case:
var someStrings = new List<string> { "Foo", "Bar", "Baz" };
new PersistenceSpecification<Foo>(CurrentSession)
.CheckComponentList(x => x.Strings, someStrings)
.VerifyTheMappings();
This code work well for me (NH 3.1, FNH 1.2). Hope this help.