I am trying to write really simple test with Mockito. I wrote small piece of code:
public class FlowTests {
#Mock
Calculator mockCalc = Mockito.mock(Calculator.class);
ConsoleView mockView = Mockito.mock(ConsoleView.class);
#Test
public void a01_Test() {
final String s = "2+2*2";
Controller c = new Controller();
c.setCalc(mockCalc);
Mockito.when(mockView.getFormule()).thenReturn(s); // I am not sure if it works
c.setView(mockView);
c.handle();
// TODO check if evaluate method has been invoked with "2+2*2"
}
}
Here you can see classes associated with this test:
public class Controller {
private IView view = new ConsoleView();
private ICalculator calc = new Calculator();
Double value = null;
public void handle() {
String formule = view.getFormule();
Double value = calc.evaluate(formule);
if (value != null) {
System.out.println("Result: ");
view.appendAnswer(value);
}
}
public void setCalc(ICalculator calc) {
this.calc = calc;
}
public void setView(IView view) {
this.view = view;
}
}
public class Calculator implements ICalculator {
public double evaluate(String s) {
...
char[] formuleChar = s.toCharArray();
result = calc.eval(formuleChar);
return result;
}
}
public class ConsoleView implements IView {
public String getFormule() {
... // getting s from console
return s;
}
public void appendAnswer(double r) {
System.out.println(r);
}
}
First goal of my test is to mock function getFormule() in ConsoleView to return always String s = "2+2*2". I did it but I am not sure if it works.
The main goal is to check if method evaluate() in Calculator class has been invoked with the same String. I have no idea how to that.
I cannot modify my code. I can only write a test.
Thank you in advance for your help!
Try something like this:
// check if evaluate method has been invoked with "2+2*2"
verify(mockCalc).evaluate("2+2*2");
Related
Hi all i receive Nullpointer when trying to execute this unit test.I want to test e class which receive 3 parameters and returns a string. I think i need to make #Before or something else but it didn't works. Do you have suggestions...Thanks !
public class UrlConstructorTest {
private UrlConstructor urlConstructor;
#Before
public void setUp() {
urlConstructor = new UrlConstructor();
}
public static final String TEST_UPDATE_MANIFEST_SR = "/packages/proxyId/test/test1/123/test3/test_test";
#Test
public void constructUpdateManifestSrInSasTokenTest() {
String result = urlConstructor.composeDeviceRegistrationUrl("test","test123","test");
System.out.println(result);
assertNotNull(result);
assertEquals(TEST, result);
}
}
UrlConstructor is define like this:
#Component
public class UrlConstructor {
And this is the method in this class:
public String composeDUrl(String deviceId, String scopeId) {
return String.format(Constants.socpe, tes, test);
}
In Junit5, you should be using #BeforeEach. Or you can get rid of that setUp method completely.
public class UrlConstructorTest {
private final UrlConstructor urlConstructor = new UrlConstructor();
public static final String TEST_SR = "/packages/proxyId/testID/product/testscope/testcomponent/coomponent_up";
#Test
public void constructTest() {
String result = urlConstructor.composeDeviceRegistrationUrl("testID","coomponent_up","testscope");
System.out.println(result);
assertNotNull(result);
assertEquals(TEST_SR, result);
}
}
I am writing unit test but I am facing an error some how. I am triyng to test my ServiceImpl just showing my entire code down below My code below;
My Service Class
#Service
public class PlaneServiceImpl implements PlaneCallerService {
private final PlaneFactory planeFactory;
public PlaneServiceImpl(PlaneFactory planeFactory) {
this.planeFactory = planeFactory;
}
#Override
public String getPlaneType(String planeType) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(planeFactory.getPlane(planeType).getType());
stringBuilder.append(" Plane has produced.");
return stringBuilder.toString();
}
Plane class down below
public interface Plane {
String getType();
}
My PlaneFactory class down below;
#Component
public class PlaneFactory {
public Plane getPlane(String planeType) {
if (StringUtils.isBlank(planeType)) {
throw new PlaneTypeNotFoundException();
}
if (planeType.equalsIgnoreCase("lightJet")) {
return new LightJet();
} else if (planeType.equalsIgnoreCase("midJet")) {
return new MidJet();
My Mock Test just down below
public class PlaneCallerServiceImplTest {
private PlaneFactory planeFactory;
private PlaneCallerService planeCallerService;
private plane plane;
#Before
public void setUp() {
planeFactory = mock(PlaneFactory.class);
planeCallerService = new PlaneCallerServiceImpl(planeFactory);
plane= mock(Plane.class);
}
#Test
public void testPlaneType() {
String planeType = "";
when(planeFactory.getPlane(planeType)).thenReturn(plane);
String result = planeCallerService.getplaneType(planeType);
assertNotNull(result);
}
}
I'm getting The method getPlane(String) is undefined for the type PlaneFactory
I am quite new for unit test and also mock test any help would be appreciate
Thank you in advanced
Your issue is that from the below statement:
when(planeFactory.getPlane(planeType)).thenReturn(plane);
you are returning a mocked response of type Plane but in that mocked response when you call Plane.getType() that method is not implemented.
You can mock the response of that too, add
when(plane.getType()).thenReturn("SOME_MOCKED_STRING");
This should start to work.
Below is the complete test class:
public class PlaneServiceImplTest {
private PlaneFactory planeFactory;
private PlaneServiceImpl planeCallerService;
#Before
public void setUp() {
planeFactory = mock(PlaneFactory.class);
planeCallerService = new PlaneServiceImpl(planeFactory);
}
#Test
public void testPlaneType() {
Plane plane = mock(Plane.class);
when(planeFactory.getPlane(anyString())).thenReturn(plane);
String result = planeCallerService.getPlaneType("Test");
assertNotNull(result);
}
}
public class MyXML {
private MessageParser messageParser;
private String valueA;
private String valueB;
private String valueC;
public MyXML (MessageParser messageParser) {
this.messageParser=messageParser;
}
public void build() {
try {
setValueA();
setValueB();
setValueC();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setValueA() {
valueA = messageParser.getArrtibuteUsingXPath("SomeXPath1...");
}
private void setValueB() {
valueB = messageParser.getArrtibuteUsingXPath("SomeXPath2...");
}
private void setValueC() {
valueC = messageParser.getArrtibuteUsingXPath("SomeXPath...");
}
public String getValueA() {
return valueA;
}
public String getValueB() {
return valueB;
}
public String getValueC() {
return valueC;
}
}
So I need to use Mockito to test the builder method. Im fairly new to Mockito could someone give me some example code as to how I might write a test for the builder method?
If you want to suggest any ways I might change the design of the class or make it easier to test let me know.
To test build() you can try :
#RunWith(MockitoJUnitRunner.class)
public class YourTest {
#Mock
private private MessageParser messageParserMock;
// this one you need to test
private MyXML myXML;
#Test
public void test() {
myXML = new MyXML(messageParserMock);
// I believe something like this should work
Mockito.doAnswer(/* check mockito Answer to figure out how */)
.when(messageParserMock).getArrtibuteUsingXPath(anyString());
// you should do this for all your 3 getArrtibuteUsingXPath because setValueA(), setValueB(), setValueC() are called that one and then call build and verify results
myXML.build(); // for instance
assertEquals("something you return as Answer", myXML.getValueA());
}
}
The resource https://static.javadoc.io/org.mockito/mockito-core/2.8.9/org/mockito/Mockito.html#stubbing_with_exceptions might be useful - it describes how to stub void methods call.
I try to create test for my presenter, but when I run it, I got this kind of error
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
ScalarSynchronousObservable cannot be returned by getContext()
getContext() should return Context
I create my presenter test class like this
public class CreateTalkPresenterTest {
#Mock
TalkService talkService;
#Mock
CreateTalkMvpView createTalkMvpView;
CreateTalkPresenter createTalkPresenter;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
talkService = ServiceFactory.createMapi(createTalkMvpView.getContext(), TalkService.class);
createTalkPresenter = new CreateTalkPresenter(Schedulers.immediate(), Schedulers.immediate());
createTalkPresenter.attachView(createTalkMvpView);
}
#Test
public void createTalkSuccessfullTest() {
TalkService.TalkResultModel talkResultModel = MockModel.newTalkResultModel();
when(talkService.createNewTalk(
FileUtil.createPartFromString("Lorem Ipsum dolor"),
FileUtil.createPartFromString("100"),
null,
FileUtil.createPartFromString("0")
)).thenReturn(Observable.just(talkResultModel));
createTalkPresenter.callCreateTalk("Lorem Ipsum dolor", "100", null);
verify(createTalkMvpView).showProgressIndeterminate();
verify(createTalkMvpView).hideProgressIndeterminate();
verify(createTalkMvpView).showTalkCreated(talkResultModel.object);
}
}
and for Mock the result I use this class
public class MockModel {
public static TalkService.TalkResultModel newTalkResultModel(){
TalkService.TalkResultModel talkResultModel = new TalkService.TalkResultModel();
talkResultModel.code = 600;
talkResultModel.message = "Successfully executed!";
talkResultModel.object = newTalkModel();
return talkResultModel;
}
public static TalkModel newTalkModel(){
Random random = new Random();
String index = String.valueOf(random.nextInt(100));
TalkModel talkModel = new TalkModel();
talkModel.id = index;
talkModel.content = "Lorem Ipsum dolor";
talkModel.categorytalk = newCategoryTalkModel("Category "+index);
talkModel.creator = newConsumerModel("User "+index);
return talkModel;
}
public static CategoryTalkModel newCategoryTalkModel(String name){
CategoryTalkModel categoryTalkModel = new CategoryTalkModel();
categoryTalkModel.id = "100";
categoryTalkModel.name = name;
return categoryTalkModel;
}
public static ConsumerModel newConsumerModel(String name){
Random random = new Random();
String index = String.valueOf(random.nextInt(100));
ConsumerModel consumerModel = new ConsumerModel();
consumerModel.id = index;
consumerModel.username = name;
consumerModel.email = name+"#domain.com";
consumerModel.fullName = "Fullname "+name;
return consumerModel;
}
}
And this is the presenter class that I want to test
public class CreateTalkPresenter implements Presenter<CreateTalkMvpView> {
private CreateTalkMvpView createTalkMvpView;
private TalkService mApiTalkService;
private TalkService.TalkResultModel talkResultModel;
private final Scheduler mainScheduler, ioScheduler;
private Subscription subscription;
public CreateTalkPresenter(Scheduler ioScheduler, Scheduler mainScheduler) {
this.ioScheduler = ioScheduler;
this.mainScheduler = mainScheduler;
}
#Override
public void attachView(CreateTalkMvpView view) {
createTalkMvpView = view;
}
#Override
public void detachView() {
createTalkMvpView = null;
unsubscribe();
}
private void unsubscribe() {
if (subscription != null) subscription.unsubscribe();
}
public void callCreateTalk(String content, String categoryId, String filePath) {
mApiTalkService = ServiceFactory.createMapi(createTalkMvpView.getContext(), TalkService.class);
unsubscribe();
createTalkMvpView.showProgressIndeterminate();
subscription = mApiTalkService.createNewTalk(
FileUtil.createPartFromString(content),
FileUtil.createPartFromString(categoryId),
filePath != null ? FileUtil.prepareFilePart("picture", new File(filePath)) : null,
FileUtil.createPartFromString("0"))
.observeOn(mainScheduler)
.subscribeOn(ioScheduler)
.subscribe(new Subscriber<TalkService.TalkResultModel>() {
#Override
public void onCompleted() {
createTalkMvpView.hideProgressIndeterminate();
createTalkMvpView.showTalkCreated(talkResultModel.object);
}
#Override
public void onError(Throwable e) {
createTalkMvpView.hideProgressIndeterminate();
WarningUtil.onApiError(createTalkMvpView.getContext(), 0, e.getMessage());
}
#Override
public void onNext(TalkService.TalkResultModel talkResultModel) {
CreateTalkPresenter.this.talkResultModel = talkResultModel;
}
});
}
}
I'm using retrofit 2.1.0 and rx android in this case.
So if someone have any idea, what I'm doing wrong in my code. Please help me
Thanks.
talkService isn't a mock. Even though you have this set:
#Mock
TalkService talkService;
You then overwrite it in your #Before method setUp:
talkService = ServiceFactory.createMapi(createTalkMvpView.getContext(), TalkService.class);
So in your test, this happens to a real TalkService implementation:
when(talkService.createNewTalk(/* ... */
)).thenReturn(Observable.just(talkResultModel));
Which then calls a real createNewTalk method, which starts with this:
mApiTalkService = ServiceFactory.createMapi(
createTalkMvpView.getContext(), TalkService.class);
The rest of the method isn't important, because Mockito's when works by mocking the last method that was called before/within the call to when, and nothing else in that method interacts with mocks. If talkService were a mock, then when(talkService.createNewTalk(/*...*/)) would stub the method createNewTalk, but instead it stubs that last mock method call getContext. This makes it look like:
when(createTalkMvpView.getContext()).thenReturn(Observable.just(talkResultModel));
...which exactly matches your error message:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
ScalarSynchronousObservable cannot be returned by getContext()
To fix this, just remove your talkService assignment so the when method call is actually a mock, or use a real talkService as you've initialized it and remove the #Mock annotation and when and verify statements.
I need to pass a string from class to another class in Java (Bukkit), I have already read some similar questions, but I can't solve the problem.
I have a Main class
public class Main extends JavaPlugin {
#Override
public void onEnable() {
new PlayerListener(this);
this.saveDefaultConfig();
String bannedBlocksString = this.getConfig().getString("bannedBlocks");
}
#Override
public void onDisable() {
}
}
And another class "PlayerListener"
public class PlayerListener implements Listener {
public PlayerListener(Main plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
// public static final String bannedBlocksString = "DIAMOND_BLOCK; EMERALD_BLOCK";
public static final String[] bannedBlocks = bannedBlocksString.split("; ");
public static boolean isBannedBlock(String[] bannedBlocks, String blockPlaced) {
boolean returnValue = false;
for (String bannedBlock : bannedBlocks) {
if(blockPlaced.equalsIgnoreCase(bannedBlock)){
returnValue = true;
}
}
return returnValue;
}
#EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
String blockPlaced = event.getBlockPlaced().getType().toString();
if(!event.getPlayer().hasPermission("antibuild.block.noplace") && isBannedBlock(bannedBlocks, blockPlaced)) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You can not place this block.");
}
}
}
How can I get the value of bannedBlocksString in Main from the class "PlayerListener"?
Try this, I hope it works:
From Main:
PlayerListener pl = new PlayerListener(this);
this.saveDefaultConfig();
String [] bannedBlocksString = pl.getBannedBlocks();
From PlayerListener you have to declare get method:
public String [] getBannedBlocks(){
return this.bannedBlocks;
}
If you uncomment the bannedBlocksString in the PlayerListener then you can always access it in the Main class using PlayerListener.bannedBlocksString as the variable is static.
If you want to do it the other way arround and assign the value you need to remove the final from the variable and use the code beneath.
PlayerListener.bannedBlocks = bannedBlocksString.split("; ");