Mocking method taking a Supplier<String> method not working - java

Given the following classes:
class Logger {
public void log(String someInfo,
String someOtherInfo,
VssNotificationStatus status,
Supplier<String> message)
{}
}
class Asset {
private String name;
private String alias;
Asset(String name, String alias) {
this.name = name;
this.alias = alias;
}
public String getName() {
return name;
}
public String getAlias() {
return alias;
}
}
class ClassUnderTest {
private Logger logger;
ClassUnderTest(Logger logger) {
this.logger = logger;
}
public void methodUnderTest(Asset asset) {
logger.log(asset.getName(), asset.getAlias(), VssNotificationStatus.ASSET_PREPARED, () -> String.format("%s is running", "methodUnderTest"));
}
}
And the following test code:
#RunWith(MockitoJUnitRunner.class)
public class TestA {
private ClassUnderTest clazz;
#Mock
private Logger logger;
#Before
public void setup() {
clazz = new ClassUnderTest(logger);
}
#Test
public void test() {
// given
String info1 = "info1";
String info2 = "info2";
Asset asset = mock(Asset.class);
given(asset.getName()).willReturn(info1);
given(asset.getAlias()).willReturn(info2);
// when
clazz.methodUnderTest(asset);
// then
verify(logger).log(eq(asset.getName()), eq(asset.getAlias()), eq(VssNotificationStatus.ASSET_PREPARED), any());
}
}
fails at the verify line with
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded
I tried to use isA(Supplier.class), specify Supplier.class in the any method, but still same error. It feels like Mockito is not mocking properly this method.
Those failing tests were passing properly before refactoring the last parameter from simple String parameter to a Supplier<String>.
I'm using mockito-core 2.13.0

It looks like Matchers doesn't like when you pass in a mocked method instead of using the value you used when mocking this method directly. The following verify works perfectly fine.
verify(logger).log(eq(info1), eq(info2), eq(VssNotificationStatus.ASSET_PREPARED), any());
So matchers should use real values and not getting them from a mocked object.

Related

ParametrizedTest with displayName and Argument

I am trying to migrate from JUnit4 to JUnit5 and also I'm new to ParametrizedTest in Junit5 and I have a scenario wherein I would like to provide different DisplayName and the Test argument(Object).
Here's the data source I would like to use as an input for #MethodSource("data")
public static Collection<Object[]> data() throws IOException {
List<Object[]> testCaseData = new ArrayList<>();
TestCaseReader testCaseReader = new TestCaseReader(TESTCASE_CSV_RESOURCE);
List<MyClass> testCaseList = testCaseReader.readTestCases();
for (MyClass testCase : testCaseList) {
if (testCase.isActive()) {
Object[] testParameter = new Object[2];
testParameter[0] = String.format("%03d: %s", testCase.getStartingLineNumber(), testCase.getName());
testParameter[1] = testCase;
testCaseData.add(testParameter);
}
}
return testCaseData;
}
And this is the Test
#ParameterizedTest(name = "Scenario: {0}, testCase={1}")
#MethodSource("data")
public void process(MyClass testCase) {
//...
//some operating on testCase methods/variables
}
When executing TestCase, I see the DisplayName is picked up correctly, but the other arguments is not resolvable it says
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [com.sample.MyClass testCase] in method [public void.MultipleTestCase.process(com.sample.MyClass testCase)]
Could you please guide me what I have done wrong here!
Thanks
Providing test data as Collection<Object[]> is no longer the appropriate way in JUnit 5. You can use a Stream instead. If you need to provide multiple parameters for your test you can use Arguments to wrap them. They are automatically unwrapped upon test execution. The example below gives a general idea on how to do that. You can replace TestCase with MyClass and insert your TestCaseReader code in data.
public class ParameterizedTest {
static Stream<Arguments> data() {
// TODO: Add your TestCaseReader usage to create MyClass / TestCase instances.
List<TestCase> testCases =
List.of(new TestCase("test01", "data01"), new TestCase("test02", "data02"));
return testCases.stream().map(test -> Arguments.arguments(test.getName(), test));
}
#org.junit.jupiter.params.ParameterizedTest(name = "Scenario: {0}, testCase={1}")
#MethodSource("data")
public void process(String name, TestCase testCase) {
System.out.println(name + ": " + testCase.getData());
// TODO: Work with your test case.
}
private static final class TestCase {
private final String name;
private final String data;
public TestCase(String name, String data) {
this.name = name;
this.data = data;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
}

Using Java 8 is there a way to validate/assert that a constant is a compile-time constant?

I'd like to have a JUnit test that verifies a specific constant is a Compile-Time Constant.
How would I go about doing that?
I found a solution for Scala, but I'd like on for plain Java.
Is there a way to test at compile-time that a constant is a compile-time constant?
Root Cause:
The value for annotation attribute ApiModelProperty.allowableValues must be a constant expression
What I'd like in a Unit Test:
validateCompileTimeConstant(SomeClass.CONSTANT_VALUE, "Message Here!!");
Usage
#ApiModelProperty(name = "name", required = true, value = "Name", allowableValues=SomeClass.API_ALLOWABLE_VALUES, notes=SomeClass.API_NOTES)
private String name;
SomeClass
public enum SomeClass {
BOB(4, "Bob"),//
TED(9, "Ted"),//
NED(13, "Ned");
public static final String API_ALLOWABLE_VALUES = "4,9,13,16,21,26,27,170";
public static final String API_NOTES = "4 - Bob\n" +
"9 - Ted\n" +
"13 - Ned";
public int code;
public String desc;
private ContentCategoryCode(int code, String desc) {
this.code = code;
this.desc = desc;
}
public static final String apiAllowableValues() {
StringBuilder b = new StringBuilder();
for (ContentCategoryCode catCode : values()) {
b.append(catCode.code);
b.append(',');
}
b.setLength(b.length()-1);
return b.toString();
}
public static final String apiNotes() {
StringBuilder b = new StringBuilder();
for (ContentCategoryCode catCode : values()) {
b.append(catCode.code).append(" - ").append(catCode.desc);
b.append('\n');
}
b.setLength(b.length()-1);
return b.toString();
}
}
The Error Prone project has a #CompileTimeConstant annotation which can be used to enforce exactly this.
It's not a test that you run with JUnit, but a compiler plug-in that enforces this (and other bug patterns) at compile time.
Here is the documentation: https://errorprone.info/bugpattern/CompileTimeConstant
I ended up creating my own annotation, since it required less setup than using Error Prone.
Annotation Class:
#Target(ElementType.METHOD)
public #interface TestCompileTimeConstant {
public String key() default "";
}
JUnit Test:
public class SomeClassTest {
#Test
public void test() {
assertEquals(SomeClass.API_ALLOWABLE_VALUES, SomeClass.apiAllowableValues());
assertEquals(SomeClass.API_NOTES, SomeClass.apiNotes());
}
#Test
#TestCompileTimeConstant(key=SomeClass.API_ALLOWABLE_VALUES)
public void testIsCompileTimeConstant1() {
//Pass - If this doesn't compile, you need to make sure API_ALLOWABLE_VALUES doesn't call any methods.
}
#Test
#TestCompileTimeConstant(key=SomeClass.API_NOTES)
public void testIsCompileTimeConstant2() {
//Pass - If this doesn't compile, you need to make sure API_NOTES doesn't call any methods.
}
}

How to mock enum.values() in mockito

First of all i'm learning java and mockito, did search and cannot find proper answer yet.
The pseudo code is like this
public enum ProdEnum {
PROD1(1, "prod1"),
PROD2(2, "prod2"),
......
PROD99(2, "prod2");
private final int id;
private final String name;
private ProdEnum(int id, String name) {
this.id = id;
this.name = name;
}
prublic String getName() { return this.name; }
}
public class enum1 {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
System.out.println("Hello, World");
List<String> prodNames = Array.stream(ProdEnum.values())
.map(prodEnum::getName)
.collect(Collectors.toList());
// verify(prodNames);
}
}
My question is in unit test, how to generate mocked prodNames ?
Only 2 or 3 of the products needed for testing,
In my unit test i tried this
List<ProdEnum> newProds = Arrays.asList(ProdEnum.PROD1, ProdEnum.PROD2);
when(ProdEnum.values()).thenReturn(newProds);
but it says Cannot resolve method 'thenReturn(java.util.List<...ProdEnum>)'
Thanks !
You cannot mock statics in vanilla Mockito.
If your up for a little refactor then:
1) Move enum.values() call into a package level method:
..
List<String> prodNames = Array.stream(getProdNames())
.map(prodEnum::getName)
.collect(Collectors.toList());
..
List<String> getProdNames(){
return ProdEnum.values();
}
2) Spy on your SUT:
enum1 enumOneSpy = Mockito.spy(new enum1());
3) Mock the getProdNames() method:
doReturn(newProds).when(enumOneSpy).getProdNames();

Annotation is null on run-time

I try to test out how an Annotation works, but doesn't go as planned. When I try to run the application everything works fine, unless the fact that ReadCommandAnnotation class is not able to retrieve the values from the Annotation from a method or class.
Now, I do not entirely know how to really do this, and I'm open for help and tips how to improve this. I have a plan why I want to use this, but right now I'm stuck at this point.
Example of what doesn't work: command, description, aliases, rank, useable
TL;DR, I want to retrieve the value from annotations from each method/class. I dont understand how to do it myself..
Register all the annotation values within this class.
public class ReadCommandAnnotation {
private final Class<?> clazz;
private String command;
private String[] description;
private boolean useable;
private String[] aliases;
private int rank;
public ReadCommandAnnotation(final Class<?> clazz) {
this.clazz = clazz.getClass();
this.register();
}
public void register() {
Method[] methods = clazz.getClass().getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(CommandAnnotation.class)) {
CommandAnnotation commandAnnotation = method.getAnnotation(CommandAnnotation.class);
this.command = commandAnnotation.command();
this.description = commandAnnotation.description();
this.useable = commandAnnotation.use();
this.rank = commandAnnotation.rankRequired();
this.alises = commandAnnotation.aliases();
}
}
}
Annotation inferface, I think everything shoud be as normal here..?
#Retention(RetentionPolicy.RUNTIME)
public #interface CommandAnnotation {
String DEFAULT_MESSAGE = "N/A";
int DEFAULT_INTEGER = 1;
String command() default DEFAULT_MESSAGE;
String[] aliases() default { DEFAULT_MESSAGE };
String[] description() default { DEFAULT_MESSAGE };
int rankRequired() default DEFAULT_INTEGER;
boolean use() default true;
The "main" class. (onEnable) method is where I run everything. (SPONGE API IS IMPLEMENTED)
#Override
public void onEnable() {
testCommandAnnotation();
}
#Override
public void onDisable() {
}
#CommandAnnotation(command = "testCommand" , aliases = {"fancyCommand", "coolCommand"} , description = {"A test command execution.."} , rankRequired = 30, use = true)
public void testCommandAnnotation() {
ReadCommandAnnotation readAnnotation = new ReadCommandAnnotation(this.getClass());
readAnnotation.register();
System.out.println("Command: " + readAnnotation.getCommand());
}
Somehow when I execute this all I get up is a "N/A" in the console.

Capturing method parameter in jMock to pass to a stubbed implementation

I wish to achieve the following behavior.
My class under test has a dependency on some other class, I wish to mock this dependency with jMock. Most of the methods would return some standard values, but there is one method, where I wish to make a call to a stubbed implementation, I know I can call this method from the will(...) but I want the method to be called by the exact same parameters that were passed to the mocked method.
Test
#Test
public void MyTest(){
Mockery context = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
IDependency mockObject = context.mock(IDependency.class);
Expectations exp = new Expectations() {
{
allowing(mockObject).methodToInvoke(????);
will(stubMethodToBeInvokedInstead(????));
}
};
}
Interface
public interface IDependency {
public int methodToInvoke(int arg);
}
Method to be called instead
public int stubMethodToBeInvokedInstead(int arg){
return arg;
}
So how do I capture the parameter that were passed to the method being mocked, so I could pass them to the stubbed method instead?
EDIT
Just to give another example, let's say I wish to mock the INameSource dependency in the following (C#) code, to test the class Speaker
public class Speaker
{
private readonly string firstName;
private readonly string surname;
private INameSource nameSource ;
public Speaker(string firstName, string surname, INameSource nameSource)
{
this.firstName = firstName;
this.surname = surname;
this.nameSource = nameSource;
}
public string Introduce()
{
string name = nameSource.CreateName(firstName, surname);
return string.Format("Hi, my name is {0}", name);
}
}
public interface INameSource
{
string CreateName(string firstName, string surname);
}
This is how it can be done in Rhino Mocks for C# I understand it can't be as easy as this since delegates are missing in Java
The solution from Duncan works well, but there is even a simpler solution without resort to a custom matcher. Just use the Invocation argument that is passed to the CustomActions invoke method. At this argument you can call the getParameter(long i) method that gives you the value from the call.
So instead of this
return matcher.getLastValue();
use this
return (Integer) invocation.getParameter(0);
Now you don't need the StoringMatcher anymore: Duncans example looks now like this
#RunWith(JMock.class)
public class Example {
private Mockery context = new JUnit4Mockery();
#Test
public void Test() {
final IDependency mockObject = context.mock(IDependency.class);
context.checking(new Expectations() {
{
// No custom matcher required here
allowing(mockObject).methodToInvoke(with(any(Integer.class)));
// The action will return the first argument of the method invocation.
will(new CustomAction("returns first arg") {
#Override
public Object invoke(Invocation invocation) throws Throwable {
return (Integer) invocation.getParameter(0);
}
});
}
});
Integer test1 = 1;
Integer test2 = 1;
// Confirm the object passed to the mocked method is returned
Assert.assertEquals((Object) test1, mockObject.methodToInvoke(test1));
Assert.assertEquals((Object) test2, mockObject.methodToInvoke(test2));
}
public interface IDependency {
public int methodToInvoke(int arg);
}
Like Augusto, I'm not convinced this is a good idea in general. However, I couldn't resist having a little play. I created a custom matcher and a custom action which store and return the argument supplied.
Note: this is far from production-ready code; I just had some fun. Here's a self-contained unit test which proves the solution:
#RunWith(JMock.class)
public class Example {
private Mockery context = new JUnit4Mockery();
#Test
public void Test() {
final StoringMatcher matcher = new StoringMatcher();
final IDependency mockObject = context.mock(IDependency.class);
context.checking(new Expectations() {
{
// The matcher will accept any Integer and store it
allowing(mockObject).methodToInvoke(with(matcher));
// The action will pop the last object used and return it.
will(new CustomAction("returns previous arg") {
#Override
public Object invoke(Invocation invocation) throws Throwable {
return matcher.getLastValue();
}
});
}
});
Integer test1 = 1;
Integer test2 = 1;
// Confirm the object passed to the mocked method is returned
Assert.assertEquals((Object) test1, mockObject.methodToInvoke(test1));
Assert.assertEquals((Object) test2, mockObject.methodToInvoke(test2));
}
public interface IDependency {
public int methodToInvoke(int arg);
}
private static class StoringMatcher extends BaseMatcher<Integer> {
private final List<Integer> objects = new ArrayList<Integer>();
#Override
public boolean matches(Object item) {
if (item instanceof Integer) {
objects.add((Integer) item);
return true;
}
return false;
}
#Override
public void describeTo(Description description) {
description.appendText("any integer");
}
public Integer getLastValue() {
return objects.remove(0);
}
}
}
A Better Plan
Now that you've provided a concrete example, I can show you how to test this in Java without resorting to my JMock hackery above.
Firstly, some Java versions of what you posted:
public class Speaker {
private final String firstName;
private final String surname;
private final NameSource nameSource;
public Speaker(String firstName, String surname, NameSource nameSource) {
this.firstName = firstName;
this.surname = surname;
this.nameSource = nameSource;
}
public String introduce() {
String name = nameSource.createName(firstName, surname);
return String.format("Hi, my name is %s", name);
}
}
public interface NameSource {
String createName(String firstName, String surname);
}
public class Formal implements NameSource {
#Override
public String createName(String firstName, String surname) {
return String.format("%s %s", firstName, surname);
}
}
Then, a test which exercises all the useful features of the classes, without resorting to what you were originally asking for.
#RunWith(JMock.class)
public class ExampleTest {
private Mockery context = new JUnit4Mockery();
#Test
public void testFormalName() {
// I would separately test implementations of NameSource
Assert.assertEquals("Joe Bloggs", new Formal().createName("Joe", "Bloggs"));
}
#Test
public void testSpeaker() {
// I would then test only the important features of Speaker, namely
// that it passes the right values to the NameSource and uses the
// response correctly
final NameSource nameSource = context.mock(NameSource.class);
final String firstName = "Foo";
final String lastName = "Bar";
final String response = "Blah";
context.checking(new Expectations() {
{
// We expect one invocation with the correct params
oneOf(nameSource).createName(firstName, lastName);
// We don't care what it returns, we just need to know it
will(returnValue(response));
}
});
Assert.assertEquals(String.format("Hi, my name is %s", response),
new Speaker(firstName, lastName, nameSource).introduce());
}
}
JMock doesn't support your use case (or any other mocking framework I know of in java).
There's a little voice in my head that says that what you're trying to do is not ideal and that your unit test might be to complicated (maybe it's testing too much code/logic?). One of the problems I see, is that you don't know which values those mocks need to return and you're plugging something else, which might make each run irreproducible.

Categories

Resources