Why are my unit tests not coming through when the original code works fine? - spring-boot

My unit test keeps on sending error messages even though the initial code works and I wrote other unit tests the same way and they work perfectly.
Initial code:
#Override
public void newOrder(OrderVO orderVO) {
OrderProduct orderProduct = new OrderProduct();
Optional<User> userResponse = userRepository.findById(orderVO.getUserId());
User user = userResponse.orElse(new User());
Orders order = new Orders(user);
orderRepository.save(order);
orderProduct.setId(new OrderProductId());
orderProduct.setOrders(order);
List<ProductVO> productVOS = orderVO.getOrderProducts();
for (ProductVO p : productVOS) {
Optional<Product> productResponse = productRepository.findById(p.getId());
Product product = productResponse.orElse(new Product());
product.setAmount(product.getAmount() - p.getAmountOfOrderedProducts());
product.setUser(user);
productRepository.save(product);
orderProduct.setProduct(product);
orderProduct.setAmountOfOrderedProduct(p.getAmountOfOrderedProducts());
orderProductRepository.saveOrder(orderProduct.getProduct().getId(), orderProduct.getOrders().getId(), orderProduct.getAmountOfOrderedProduct());
}
}
test:
#Test
void newOrder() {
User userTest = new User(1);
Optional<User> optUserTest = Optional.of(userTest);
Optional<Product> optProductTest = Optional.of(productTest);
OrderVO orderVO = new OrderVO();
Orders orders = new Orders(userTest);
when(userRepository.findById(anyInt())).thenReturn(optUserTest);
when(productRepository.findById(anyInt())).thenReturn(optProductTest);
orderService.newOrder(orderVO);
verify(productRepository, times(1)).save(productTest);
verify(orderRepository, times(1)).save(orders);
verify(orderProductRepository, times(1)).saveOrder(1,1,53);
}
I keep on getting two errors:
first one is pointing to verify(productRepository, times(1)).save(productTest);
and says that
Wanted but not invoked:
productRepository.save(
com.carlsberg.orderservice.domains.Product#a1db9da0
);
-> at com.carlsberg.orderservice.serviceImpl.OrderServiceImplTest.newOrder(OrderServiceImplTest.java:78)
Actually, there were zero interactions with this mock.
Second one points to verify(orderRepository, times(1)).save(orders);
and the error message is
Argument(s) are different! Wanted:
orderRepository.save(
com.carlsberg.orderservice.domains.Orders#d7c7950f
);
The difference seems to be in d7c7950f part.
This is my first time trying to do unit testing. Really not sure why am I getting this errors since the same concept of writing unit tests worked just fine on other methods.

The first error is due to the fact that your test never coverages a case where there are ProductVos in tested OrderVO. That makes stubbing that method to be 'wrong' since the method is invoked only in a loop that goes through ProductVOs.
Try to add some ProductVOs if it helps for this. Maybe you still might want to test with 0 1 and many OrderVOs in 0 case just remove the stubbing as it is not needed
The second one is a bit more complicated, in touyr service you have:
Orders order = new Orders(user);
orderRepository.save(order);
on the other hand in your test you have:
Orders orders = new Orders(userTest);
the is no path that saves the orders you created in your test , it is alwasy created in the service and the hassh is thus also different. I guess this error goes away when you change verify to, say:
verify(orderRepository, times(1)).save(any());
but the test is bad and you should fix it to use the orders you create in test.

Related

Single Responsibility Principle, Test Driven Development, and Functional Design

I am fairly new to Test Driven Development and I just started learning the SOLID principles so I was hoping someone could help me out. I'm having some conceptual trouble understanding the Single Responsibility Principle in the context of developing unit tests and methods in the TDD paradigm. For instance, say I want to develop a method that deletes an item from a database- before my code would have looked like the following...
I'd start with defining a test case:
"Delete_Item_ReturnsTrue": function() {
//Setup
var ItemToDelete = "NameOfSomeItem";
//Action
var BooleanResult = Delete( ItemToDelete );
//Assert
if ( BooleanResult === true ) {
return true;
} else {
console.log("Test: Delete_Item_ReturnsTrue() - Failed.");
return false;
}
}
I'd run the test to make sure it failed, then I'd develop the method...
function Delete( ItemToDelete ) {
var Database = ConnectToDatabase();
var Query = BuildQuery( ItemToDelete );
var QueryResult = Database.Query( Query );
if ( QueryResult.error !== true ) {
//if there's no error then...
return true;
} else {
return false;
}
}
If I'm understanding the Single Responsibility Principle correctly, the method that I originally wrote had the responsibilities of deleting the item AND returning true if there wasn't an error. So if I follow the SOLID paradigm the original method should be refactored to look something like...
function Delete( WhatToDelete, WhereToDeleteItFrom ) {
WhereToDeleteItFrom.delete( WhatToDelete );
}
Doing the design as such, changed my method from a boolean function to a void function so now I can't really test the new method in the same manner I was testing my old method.
I guess I could test for thrown exceptions but then doesn't that make it an integration test rather than a unit test because there's no actual exception thrown in the method?
Do I design and implement an extra function which checks the database for use in my unit test?
Do I just not test it because it's void? How exactly does that work in TDD?
Do I pass in a mock repository and then return it after it's state has changed? Doesn't that just essientially bring me back to square one?
Do I pass in a reference to a mock repository and then just test against the repository after the method completes? Wouldn't that be considered a side effect though?
So the single responsibility principle says: They should be exact one reason when I need to change a function.
So let's look at your function:
function Delete( ItemToDelete ) {
var Database = ConnectToDatabase();
var Query = BuildQuery( ItemToDelete );
var QueryResult = Database.Query( Query );
if ( QueryResult.error !== true ) {
//if there's no error then...
return true;
} else {
return false;
}
}
Database changes: ConnectToDatabese() needs a change, but not this function
Changes in the db structure: BuildQuery() needs to be changed (maybe)
...
So on the first look, your function looks good. The naming on some places is a little bit confusing. A function should be start with a small letter. For example "connectToDatabase()". It is a little bit surprising that connectToDatabase returns an Object.
The name BuildQuery seems to be wrong, because BuildQuery( myItem ) returns a query wich is deleting something.
But I would never have such a long complicated function which just one testcase.
You need to write more test cases.
For the first test case you could write the function like that:
function Delete( ItemToDelete) {
return true
}
The next testcase could be "call the buildDeleteQuery function with the item id". At that point you need to think about how you call your db. If you have a dbObject, which does that you could mock that Object.
function Delete( ItemToDelete ) {
buildDeleteQuery( ItemToDelete.id )
return true
}
Now more and more test cases. Remember that there will be also test cases for buildDeleteQuery. But for the outer function you could mock buildDeleteQuery.
Now to answer some of your questions:
When you first write the test and then write the code, you will have testable code.
That code looks different, because the tests should be not to complicated. When you want easy tests you will automaticly have more smaller functions.
Yes, you will write a test for every function you call.
Maybe you will mock objects. And if you are not able to test your db call without a wrapping function you will create a function, which allows you to test that functionality.
Remember your tests are the documentation of your code. So keep them simple as possible.
But the most important thing: Keep practicing! When you start with TDD it takes some time. A good and fun resource is: Uncle Bobs Bowling Kata Just download the slides from the website and look how tdd is done step by step.

ArrayListModel will not sync with JList

I have combed through SO, and have found many questions on the topic of my problem but do not answer it.
I am setting up an MVC, I have set up things correctly to best of my knowledge but I cannot get the Controller to show in my view. I am working on an assignment that essentially is a program for a Video Rental Store.
First, In a class called RentalStoreGUI, I set up my panels and everything looks good when I run.
RentalStoreEngine model = new RentalStoreEngine();
JList<DVD> list = new JList<DVD>();
list.setModel(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setVisible(true);
list.setSelectedIndex(0);
jScrollPane = new JScrollPane(list);
add(jScrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
As you can see I set my model for the list based on another class called RentalStoreEngine() and it implements AbstractListModel. The Abstract List model is functioning when I do class specific testing and all of the necessary methods are implemented. Here is an example of my add method from that class:
public void add(DVD d){
if (d != null){
rentals.add(d);//rentals is an arrayList<DVD> instantiated earlier
fireIntervalAdded(this, rentals.size() - 1, rentals.size() - 1);
}
}
Here is the actionPerformed method, it runs DVD_Dialog which simply gets some input from the user and creates a new DVD object from that.
public void actionPerformed(ActionEvent event) {
if(event.getSource() == rentDVD){
DVD_Dialog = new RentDVDDialog(this, null);
DVD_Dialog.clear();
DVD_Dialog.setVisible(true);
dvd = new DVD(DVD_Dialog.getTitleText(),DVD_Dialog.getRenterText(),
DVD_Dialog.getRentedOnText(), DVD_Dialog.getDueBackText());
if(DVD_Dialog.closeStatus() == true){
model.add(dvd);
}
}
Eclipse gives me no errors, until I run it. I then receive a nullPointerException at the line model.add(dvd); Based on all my research the list.setModel(model) and the fireIntervalAdded method line should update the Jlist on its own. But it does not. And as I said, class specific testing for both the GUI and the Model are producing the desired results, but when it comes to integrating them I am at a loss.

Domain Driven Design - complex validation of commands across different aggregates

I've only began with DDD and currently trying to grasp the ways to do different things with it. I'm trying to design it using asynchronous events (no event-sourcing yet) with CQRS. Currently I'm stuck with validation of commands. I've read this question: Validation in a Domain Driven Design , however, none of the answers seem to cover complex validation across different aggregate roots.
Let's say I have these aggregate roots:
Client - contains list of enabled services, each service can have a value-object list of discounts and their validity.
DiscountOrder - an order to enable more discounts on some of the services of given client, contains order items with discount configuration.
BillCycle - each period when bills are generated is described by own billcycle.
Here's the usecase:
Discount order can be submitted. Each new discount period in discount order should not overlap with any of BillCycles. No two discounts of same type can be active at the same time on one service.
Basically, using Hibernate in CRUD style, this would look something similar to (java code, but question is language-agnostic):
public class DiscountProcessor {
...
#Transactional
public void processOrder(long orderId) {
DiscOrder order = orderDao.get(orderId);
BillCycle[] cycles = billCycleDao.getAll();
for (OrderItem item : order.getItems()) {
//Validate billcycle overlapping
for (BillCycle cycle : cycles) {
if (periodsOverlap(cycle.getPeriod(), item.getPeriod())) {
throw new PeriodsOverlapWithBillCycle(...);
}
}
//Validate discount overlapping
for (Discount d : item.getForService().getDiscounts()) {
if (d.getType() == item.getType() && periodsOverlap(d.getPeriod(), item.getPeriod())) {
throw new PeriodsOverlapWithOtherItems(...);
}
}
//Maybe some other validations in future or stuff
...
}
createDiscountsForOrder(order);
}
}
Now here are my thoughts on implementation:
Basically, the order can be in three states: "DRAFT", "VALIDATED" and "INVALID". "DRAFT" state can contain any kind of invalid data, "VALIDATED" state should only contain valid data, "INVALID" should contain invalid data.
Therefore, there should be a method which tries to switch the state of the order, let's call it order.validate(...). The method will perform validations required for shift of state (DRAFT -> VALIDATED or DRAFT -> INVALID) and if successful - change the state and transmit a OrderValidated or OrderInvalidated events.
Now, what I'm struggling with, is the signature of said order.validate(...) method. To validate the order, it requires several other aggregates, namely BillCycle and Client. I can see these solutions:
Put those aggregates directly into the validate method, like
order.validateWith(client, cycles) or order.validate(new
OrderValidationData(client, cycles)). However, this seems a bit
hackish.
Extract the required information from client and cycle
into some kind of intermediate validation data object. Something like
order.validate(new OrderValidationData(client.getDiscountInfos(),
getListOfPeriods(cycles)).
Do validation in a separate service
method which can do whatever it wants with whatever aggregates it
wants (basically similar to CRUD example above). However, this seems
far from DDD, as method order.validate() will become a dummy state
setter, and calling this method will make it possible to bring an
order unintuitively into an corrupted state (status = "valid" but
contains invalid data because nobody bothered to call validation
service).
What is the proper way to do it, and could it be that my whole thought process is wrong?
Thanks in advance.
What about introducing a delegate object to manipulate Order, Client, BillCycle?
class OrderingService {
#Injected private ClientRepository clientRepository;
#Injected private BillingRepository billRepository;
Specification<Order> validSpec() {
return new ValidOrderSpec(clientRepository, billRepository);
}
}
class ValidOrderSpec implements Specification<Order> {
#Override public boolean isSatisfied(Order order) {
Client client = clientRepository.findBy(order.getClientId());
BillCycle[] billCycles = billRepository.findAll();
// validate here
}
}
class Order {
void validate(ValidOrderSpecification<Order> spec) {
if (spec.isSatisfiedBy(this) {
validated();
} else {
invalidated();
}
}
}
The pros and cons of your three solutions, from my perspective:
order.validateWith(client, cycles)
It is easy to test the validation with order.
#file: OrderUnitTest
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build();
subject.validateWith(client, cycles);
assertThat(order.getStatus(), is(VALID));
}
so far so good, but there seems to be some duplicate test code for DiscountOrderProcess.
#file: DiscountProcessor
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build()
DiscountProcessor subject = ...
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
given(orderRepository).findBy(order.getId()).thenReturn(order);
subject.processOrder(order.getId());
assertThat(order.getStatus(), is(VALID));
}
#or in mock style
#Test public void should_change_to_valid_when_xxxx() {
Client client = mock(Client.class)
BillCycle[] cycles = array(mock(BillCycle.class))
Order order = mock(Order.class)
DiscountProcessor subject = ...
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
given(orderRepository).findBy(order.getId()).thenReturn(order);
given(client).....
given(cycle1)....
subject.processOrder(order.getId());
verify(order).validated();
}
order.validate(new OrderValidationData(client.getDiscountInfos(),
getListOfPeriods(cycles))
Same as the above one, you still need to prepare data for both OrderUnitTest and discountOrderProcessUnitTest. But I think this one is better as order is not tightly coupled with Client and BillCycle.
order.validate()
Similar to my idea if you keep validation in the domain layer. Sometimes it is just not any entity's responsibility, consider domain service or specification object.
#file: OrderUnitTest
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build();
Specification<Order> spec = new ValidOrderSpec(clientRepository, cycleRepository);
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
subject.validate(spec);
assertThat(order.getStatus(), is(VALID));
}
#file: DiscountProcessor
#Test public void should_change_to_valid_when_xxxx() {
Order order = new OrderFixture()...build()
Specification<Order> spec = mock(ValidOrderSpec.class);
DiscountProcessor subject = ...
given(orderingService).validSpec().thenReturn(spec);
given(spec).isSatisfiedBy(order).thenReturn(true);
given(orderRepository).findBy(order.getId()).thenReturn(order);
subject.processOrder(order.getId());
assertThat(order.getStatus(), is(VALID));
}
Do the 3 possible states reflect your domain or is that just extrapolation ? I'm asking because your sample code doesn't seem to change Order state but throw an exception when it's invalid.
If it's acceptable for the order to stay DRAFT for a short period of time after being submitted, you could have DiscountOrder emit a DiscountOrderSubmitted domain event. A handler catches the event and (delegates to a Domain service that) examines if the submit is legit or not. It would then issue a ChangeOrderState command to make the order either VALIDATED or INVALID.
You could even suppose that the change is legit by default and have processOrder() directly take it to VALIDATED, until proven otherwise by a subsequent INVALID counter-order given by the validation service.
This is not much different from your third solution or Hippoom's one though, except every step of the process is made explicit with its own domain event. I guess that with your current aggregate design you're doomed to have a third party orchestrator (as un-DDD and transaction script-esque as it may sound) that controls the process, since the DiscountOrder aggregate doesn't have native access to all information to tell if a given transformation is valid or not.

Can you record accessed methods in Visual Studio?

I'm retroactively documenting and writing unit tests for some C# code. I would like to determine what code is actually being used and when.
In Visual Studio 2012, is there a way to record all the methods accessed and in what order while walking through specific scenarios?
You could run your application with a profiler attached, which will give you all accessed methods, call chains, counts, etc.
The Visual Studio Profiler will give you the time spent in each method, and let you inspect the call heirarchy. I don't know if it will give you the exact order they were called in though.
EDIT: Apparently attaching the profiler to a running unit test is harder in VS2012.
Are you wanting to execute a test method that make sure that a particular method on a class was invoked ? If so i dont know of a way to do it in VS alone, but you can use a mock framework to create dependency mocks and check values on them. Here is a snippet of a unit test:
[TestMethod]
public void HttpPostPrivacyPolicyFacadeSvcErrorTest()
{
var controller = ControllerHelper.GetRouteController();
controller.Session[SessionVariable.User] = new UserInfo() { UserName = Config.Data.Username };
var idmSvcMock = new Mock<IUserServiceDAO>();
var facadeSvcMock = new Mock<IFacadeSvcDAO>();
//setup the facade mock to throw exception to simulate FacadeServiceException
facadeSvcMock.Setup(x => x.SetPrivacyAcceptanceStatus(It.IsAny<UserInfo>())).Throws<Exception>();
var userCollectorMock = new Mock<IUserInfoCollector>();
userCollectorMock.Setup(x => x.GetUserInfo()).Returns(new UserInfo() { UserName = Config.Data.Username });
controller.FacadeSvc = facadeSvcMock.Object;
controller.UserServiceDAO = idmSvcMock.Object;
controller.UserCollector = userCollectorMock.Object;
controller.DefaultErrorId = "Route_errors_Unabletoprocess";
//action
var res = controller.Privacy(new FormCollection());
//assert
//make sure we go to the right controller, action, with the correct params.
res.AssertActionRedirect().ToController("Errors").ToAction("Index").WithParameter("id", "Route_errors_Unabletoprocess");
//did we call setprivacy once on the mock?
facadeSvcMock.Verify(x => x.SetPrivacyAcceptanceStatus(It.IsAny<UserInfo>()), Times.Exactly(1));
In the test above i check that SetPrivacyAcceptance was invoked once and only once on my facadeSvcMock instance. More on moq here: Moq
this block of code is actually checking how many times SetPrivacyAcceptanceStatus was invoked:
//did we call setprivacy once on the mock?
facadeSvcMock.Verify(x => x.SetPrivacyAcceptanceStatus(It.IsAny()), Times.Exactly(1));
the It.IsAny() is the one parameter to that method, so the line above says basically "For any input parameter of type UserInfo verify that we invoked SetPrivacyAcceptanceStatus exactly once."

MVP with Moq - loading a mocked view

I've read a lot about mocking/stubbing/faking - and still hit my mental roadblocks.
I'm trying to adapt MVP (Model View Presenter) with a "fun" weight loss tracking system I'm building for my own Fatty McFatter-self. I'm trying to TDD & 'by the book' this but hit many mental blocks and stall out.
I am building my Presenter and mocking my Service & View at the moment. Here's my test: again note: service and view are mocked with Moq
[Test]
public void GetLog_WithExistingDate_ViewSetWithExistingLog()
{
WeightLogModel model = new WeightLogModel
{
EntryDate = DateTime.Now,
Waist = 42,
Weight = 242
};
service.Setup(x => x.GetLog(It.IsAny<DateTime>())).Returns(model);
presenter.Display(DateTime.Now);
IWeightLogView myView = view.Object;
Assert.AreEqual(model.Weight, myView.Weight);
}
and in my Presenter - this is my Display method:
public void Display(DateTime date)
{
var weightLog = service.GetLog(date);
if(weightLog == null) return;
View.EntryDate = weightLog.EntryDate;
View.Waist = weightLog.Waist;
View.Weight = weightLog.Weight;
}
Now - if I debug as Display is being called - I see the weightLog is filled with the correct info I've setup in the mock. But as it's suppose to set View.EntryDate, View.Waist, etc - the View values never change. They stay zero or 0001/1/1
Is there some way to make it work? Or is this just a bad test and I'm floundering in confusion?
Thanks to Phil for starting me in motion. Although I didn't want to explicitly set what I was going to return - I wanted the mock view to behave like my view. You can have the mocked setter behave as normal by calling SetupProperty --> view.SetupProperty(x => x.Weight) //in my case... here's the test that will now pass asserting the weight was set
[Test]
public void GetLog_WithExistingDate_ViewSetWithExistingLog()
{
WeightLogModel model = new WeightLogModel
{
EntryDate = DateTime.Now,
Waist = 42,
Weight = 242
};
service.Setup(x => x.GetLog(It.IsAny<DateTime>())).Returns(model);
// I ADDED THIS ONE LINE
view.SetupProperty(x => x.Weight);
presenter.Display(DateTime.Now);
IWeightLogView myView = view.Object;
Assert.AreEqual(model.Weight, myView.Weight);
}
You are not showing all your setup code here, nor the dependencies between classes.
However if you are indeed mocking the view called "myView", it's going to return what you have the mock set up to return, or defaults for each type if you haven't specified anything for it to return (which sounds like what is happening).
From your comment:
I am trying to setup the
service.GetLog(date) to return the
WeightLogModel I have in the test. My
thinking is that doing so - would make
that WeightLogModel available in my
presenter
So far that seems like it is working from your original question.
to assign to my mocked view - where
View.EntryDate = weightLog.EntryDate
.... in this case weightLog is what is
setup in the test.... I hope I'm clear
as to where my head is... I'm not
saying I'm right - this is what my
thinking is though.
Where are you going wrong is where you say "to assign to my mocked view". It's not clear from your code whether or not the View property is in fact your mocked view (because your code is incomplete).
Although, in this case, it actually doesn't matter. If the View property is in fact a mock, it will only return what you tell it to return--its properties are not going to behave like "normal" properties.
So the following will fail without explicit setup:
mockView.MyProperty = "hello";
Assert.AreEqual("hello", mock.MyProperty);

Resources